Entity Framework 1 to 1 relationship Code First Method


/ Published in: C#
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. public class Bakery
  2. {
  3. public int BakeryId { get; set; }
  4.  
  5. public string Name { get; set; }
  6.  
  7. public virtual BakeryRecipe BakeryRecipe { get; set; }
  8. }
  9.  
  10. public class BakeryRecipe
  11. {
  12. public int BakeryRecipeID { get; set; }
  13.  
  14. public int Rank { get; set; }
  15.  
  16. public virtual Bakery Bakery { get; set; }
  17. }
  18.  
  19. public class BakeryContext: DbContext
  20. {
  21. public DbSet<Bakery> Bakery { get; set; }
  22. public DbSet<BakeryRecipe> BarkeryRecipe { get; set; }
  23.  
  24. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  25. {
  26. modelBuilder.Entity<BakeryRecipe>()
  27. .HasKey(t => t.BakeryRecipeID);
  28.  
  29. modelBuilder.Entity<Bakery>()
  30. .HasRequired(t => t.BakeryRecipe)
  31. .WithRequiredPrincipal(t => t.Bakery);
  32. }
  33. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.