简体   繁体   中英

Entity Framework properties how does it work

Here are four different approaches to defining an Entity class in Entity Framework. 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. 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.

  2. Having an AddressId as a FK for Address navigation property essentially converts your User-Address association to a "Foreign Key Association". 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. EF will do that for you automatically if you include them in your queries.

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