/ Published in: C#
![](/img/icon_sav.png?v3)
How to create a one to one relationship using the Entity Framework and the Code First Method.
In this example, were creating a 1 to 1 relationship with the Bakery class and the BakeryRecipe class.
Make sure each class has a link to the other class through the virtual instance.
Add the context code to the Context file (BakeryContext.cs in this case).
The context code below is making the Primary key in the BakeryRecipe class, and the Foreign key in the Bakery class.
In this example, were creating a 1 to 1 relationship with the Bakery class and the BakeryRecipe class.
Make sure each class has a link to the other class through the virtual instance.
Add the context code to the Context file (BakeryContext.cs in this case).
The context code below is making the Primary key in the BakeryRecipe class, and the Foreign key in the Bakery class.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
public class Bakery { public int BakeryId { get; set; } public string Name { get; set; } public virtual BakeryRecipe BakeryRecipe { get; set; } } public class BakeryRecipe { public int BakeryRecipeID { get; set; } public int Rank { get; set; } public virtual Bakery Bakery { get; set; } } public class BakeryContext: DbContext { public DbSet<Bakery> Bakery { get; set; } public DbSet<BakeryRecipe> BarkeryRecipe { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<BakeryRecipe>() .HasKey(t => t.BakeryRecipeID); modelBuilder.Entity<Bakery>() .HasRequired(t => t.BakeryRecipe) .WithRequiredPrincipal(t => t.Bakery); } }
Comments
![RSS Feed for Comments RSS Icon](/images/rss.png?v3)