简体   繁体   English

我应该将外键表存储为Entity Framework中的外键ID还是该表的C#模型?

[英]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. 假设我有一个Student班,一个Student属于School班,一个School可以有很多学生。 What we then tend to write for the School model is: 然后,我们倾向于为School模型编写的是:

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

And for the Student model: 对于Student模型:

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. 因此,您可以看到,由于有EF魔术,我们没有在Student类中使用外键 SchoolID ,而是映射了实际的School对象 ,并且将其标记为虚拟,因此也可以延迟加载。

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? 现在,这是否意味着使用EF我们可以安全地删除POCO模型中的所有外键ID,并用对这些对象的实际引用替换它们? Will there be any downside to directly referencing the object instead of IDs? 直接引用对象而不是ID是否有不利之处?

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. 如果学生更换学校,则仅希望通过了解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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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