为什么"it is recommended to include foreign key property in the entity class"?



示例中的代码:

public class Student
{
    public Student() { }
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public int StdandardRefId { get; set; }
    [ForeignKey("StandardRefId")]
    public virtual Standard Standard { get; set; }
}
public class Standard
{
    public Standard()
    {
        StudentsList = new List<Student>();
    }
    public int StandardId { get; set; }
    public string Description { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

想象一个场景,您想要设置关系,但内存中没有Standard实例,只有StandardId。这将要求您首先在数据库上执行查询以检索所需的Standard实例,以便设置Standard导航属性。有时,内存中可能没有对象,但您可以访问该对象的键值。使用外键属性,您可以简单地使用键值,而不依赖于内存中是否有该实例:

 int standardId=2;
 //...
 student.StdandardRefId =standardId;

总之,对于FK特性,您将有两个选项来设置关系。

我的建议是,当您需要创建与现有Standard相关的新Student时,请设置FK属性,而不是导航属性。在某些情况下,实体框架会将Standard的状态设置为Added,即使它已经存在于数据库中,这可能会导致数据库中出现重复。如果您只使用外键,则可以避免此问题。

通过指定虚拟Standard Standard属性,您已经告诉Entity Framework您的Student对象与零个或一个Standard对象相关。

为了让Entity Framework使用Lazy Loading自动检索此对象(由于您指定了虚拟),您还必须通过给它一个外键注释来告诉它对象之间的确切关系。当您第一次尝试访问Standard属性时,实体框架将自动尝试在其主键与外键匹配的上下文中查找匹配的Standard对象。

如果未指定关系,则可以手动检索Standard对象并使用特性的set访问器。

相关内容

最新更新