Print Page | Close Window

Still need foreign key properties in CodeFirst?

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2010
Forum Discription: For .NET 4.0
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=3014
Printed Date: 25-May-2025 at 4:55pm


Topic: Still need foreign key properties in CodeFirst?
Posted By: s_tristan
Subject: Still need foreign key properties in CodeFirst?
Date Posted: 15-Oct-2011 at 11:35am
In Code First DbContect we can simply avoid using fk properties with that fluent mapping:
modelBuilder.Entity<Parent>().HasMany(parent=>parent.Children).WithRequired(child=>child.Parent);

Is this enough or DevForce needs this fk properties for it's internal infrastructure? Are additional benefits of using fk properties present?



Replies:
Posted By: DenisK
Date Posted: 17-Oct-2011 at 12:14pm
Hi s_tristan;

What do you mean by using "fk properties"? Do you mean using the ForeignKeyAttribute?


Posted By: s_tristan
Date Posted: 17-Oct-2011 at 12:31pm
    public class Parent
    {
        public RelatedEntityList<Child> Children { getset; }
    }
 
    public class Child
    {
        public Parent Parent { getset; }
        public int ParentId { getset; } // can we omit this "buddy" property according this blog post http://msdn.microsoft.com/en-us/data/hh134698
    }
 
    public class MyDbContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Parent>().HasMany(parent => parent.Children).WithRequired(child => child.Parent);
        }
    }


Posted By: DenisK
Date Posted: 17-Oct-2011 at 1:06pm
Yes, you can omit the fk property if you have specify the fluent mapping. What EF Code First will do behind the scene is generate a Parent_ParentId field on the db table.


Posted By: s_tristan
Date Posted: 17-Oct-2011 at 1:08pm
Thank you!



Print Page | Close Window