简体   繁体   English

实体框架属性如何工作

[英]Entity Framework properties how does it work

Here are four different approaches to defining an Entity class in Entity Framework. 这是在Entity Framework中定义Entity类的四种不同方法。 Can someone tell me what is the difference in the way each approach works and also recommend which of these approaches to use? 有人可以告诉我每种方法的工作方式有何不同,并建议使用哪种方法?

// Approach 1
public class User
{
    public int Id { get; set; }
    public Address Address { get; set; }
}

// Approach 2
public class User
{
    public int Id { get; set; }
    public Address Address { get; set; }

    public User()
    {
        this.Address = new Address();
    }

}

// Approach 3
public class User
{
    public int Id { get; set; }
    public virtual Address Address { get; set; }
}

// Approach 4
public class User
{
    public int Id { get; set; }
    public virtual Address Address { get; set; }

    public User()
    {
        this.Address = new Address();
    }

}

Can I please ask for any good explanation of the differences? 我可以请您对这些差异进行任何很好的解释吗?

Are the differences related to Lazy loading vs. Eager loading? 差异是否与延迟加载和渴望加载有关?

Which is better and why? 哪个更好?为什么?

Here is how it should look like: 它看起来应该像这样:

public class User
{
    public int Id { get; set; }

    public int AddressId { get; set; }

    public virtual Address Address { get; set; }    
}


Explanations: 说明:

  1. We need to mark our navigation properties as virtual to enable EF lazy loading at runtime. 我们需要将导航属性标记为virtual以在运行时启用EF延迟加载。 EF creates a user proxy object inheriting from your user class and marking Address as virtual allows EF to override this property and add lazy loading support code. EF创建了一个从您的用户类继承的用户代理对象,并将Address标记为virtual允许EF覆盖此属性并添加延迟加载支持代码。

  2. Having an AddressId as a FK for Address navigation property essentially converts your User-Address association to a "Foreign Key Association". 使用AddressId作为FK进行“地址”导航属性实际上会将您的“用户地址”关联转换为“外键关联”。 These type of associations are preferred since they are easier to work with when it comes to updates and modifications. 这些类型的关联是首选的,因为它们在更新和修改时更易于使用。

  3. Unless you have a navigation property in the form of collection of objects (eg IList<Address> ) you don't need to initialize it in your constructor. 除非您具有对象集合形式的Navigation属性(例如IList<Address> ),否则不需要在构造函数中对其进行初始化。 EF will do that for you automatically if you include them in your queries. 如果您将EF包括在查询中,EF会自动为您完成。

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

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