Entity Framework Code First Lazy Loading

前端 未结 2 768
一整个雨季
一整个雨季 2020-11-30 01:27

I am having two object classes

public class User
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    // Navigation
    public IColle         


        
相关标签:
2条回答
  • 2020-11-30 01:43

    I guess you're quiring for a property which is a subject for lazy load while being into the ef context:

    using (var db = new Context())
    {
        var user = db.Users.Where(...);
    
        var products = user.Products; // being loaded right away
    }
    

    Try to leave it:

    User user;
    using (var db = new Context())
    {
        user = db.Users.Where(...);
    
        // I guess you will need here:
        // .Include(u => u.Products)
    }
    var products = user.Products; // what error will you get here?
    
    0 讨论(0)
  • 2020-11-30 02:03

    This is wrong

    "virtual" keyword is used for not loading the entities unless you explicit this (using an "Include" statement)

    Lazy Loading means that entities will be automatically loaded when you first access collection or navigation property, and that will happen transparently, as though they were always loaded with parent object.

    Using "include" is loading on demand, when you specify properties you want to query.

    Existence of virtual keyword is related only to lazy loading. virtual keyword allows entity framework runtime create dynamic proxies for your entity classes and their properties, and by that support lazy loading. Without virtual, lazy loading will not be supported, and you get null on collection properties.

    Fact is that you can use "include" in any case, but without lazy loading it is the only way to access collection and navigation properties.

    0 讨论(0)
提交回复
热议问题