Return to Snippet

Revision: 64713
at September 11, 2013 06:07 by heathbo


Initial Code
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);
        }
    }

Initial URL

                                

Initial Description
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.

Initial Title
Entity Framework 1 to 1 relationship Code First Method

Initial Tags

                                

Initial Language
C#