EntityFramework 6 DatabaseFirst disable lazy loading

How to disable all lazy loading

After creating the model from the database first I

public partial class company
{
    public int id { get; set; }
    public string name { get; set; }
    public virtual ICollection<user> user { get; set; }
}

public partial class user
{
    public int id { get; set; }
    public int company_id { get; set; }
    public virtual company company { get; set; }
}

      

I only want to upload a user and my company

db = new Entities();
db.Configuration.ProxyCreationEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
var result = db.user.Include(x => x.company).ToList();

      

I don't want to download the result [0] .company.user

The collection is now populated by all users of the company

result [0] .company.user must be null

if i want to load result [0] .company.user i want to use .Include (x => x.company.user)

+3


source to share


1 answer


This is not lazy loading, but another concept called relationship commit. In short, it just syncs the navigation properties with each other. In your case, you have a navigation user.company

property and a navigation property for the collection company.user

. You load a user and a company and they are contextualized. Now at some points (you can find a list of such points here ) EF performs ratio correction. In this case, it happens after the request is executed using the DbSet. EF makes sure that if user.company

set - the company.user

collection must also contain thisuser

because these are related navigation properties. This user is already bound to the context (you originally loaded it with your query), so no additional queries are added to the database, so it is not lazy.

On lazy loading, if you have 100 users for company A then it companyA.user

will contain 100 records (loaded from the database when this property is accessed). In your case, even if company A has 100 users - it companyA.user

will only contain 1 user - the one you originally uploaded.



This behavior is usually fine, although it can cause problems in some cases - most often it happens when you want to serialize your EF object and step on circular references because of it.

There is no way to disable this behavior that I am aware of.

+4


source







All Articles