简体   繁体   中英

Should I store foreign key table as foreign key ID or the C# model of that table in Entity Framework?

The title is a bit confusing but I couldn't think of any other way to put it. So I'll explain with an example.

Let's say I have a Student class, a Student belongs to a School class and a School can have many students. What we then tend to write for the School model is:

public class School
{
    public int ID { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

And for the Student model:

public class Student
{
    public int ID { get; set; }
    public virtual School School { get; set; }
}

So you can see that instead of having a foreign key SchoolID in Student class, we have an actual School object mapped thanks to EF magic, and it's marked virtual so it's lazy-loaded too.

Now does this mean that using EF we are safe to eliminate all foreign key IDs in a POCO model and replace them with actual references to those objects? Will there be any downside to directly referencing the object instead of IDs?

I think eventually you'll need the foreign key property.
If the student changes school you will want to update the Associated property only by knowing the SchoolId.

Also,if you want to add a new Student to an existing school you'll have to load the School from the same context or else you'll end up with duplicate records

So, add the Foreign Key property too

public int SchoolId{ get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM