Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework 6 DatabaseFirst disable lazy loading

How disable all lazy loading

After generation model from database first I have

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 want load only user and their 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 load result[0].company.user

Now collection filled with all users of company

result[0].company.user must be null

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

like image 516
Alexandr Sulimov Avatar asked Feb 15 '26 19:02

Alexandr Sulimov


1 Answers

This is not lazy-loading but a different concept called relationship fix-up. In short it just keeps navigation properties in sync with each other. In your case you have user.company navigation property and company.user collection navigation property. You load both user and company and they are attached to the context. Now at certain points (list of such points you can find here) EF performs relationship fix-up. In this case it happens after query is performed against DbSet. EF ensures that if user.company is set - company.user collection should contain that user also, because those are related navigation properties. This user is already attached to the context (you originally loaded it with your query) so no additional queries are made to database, so it's not lazy loading.

With lazy loading, if you have 100 users for company A then companyA.user will contain 100 entries (loaded from database when you access this property). In your case, even if company A has 100 users - companyA.user will contain just 1 user - that one which you originally loaded.

This behaviour is usually fine, though in some cases it might cause troubles - most often this happens when you want to serialize your EF object and step into circular references because of that.

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

like image 51
Evk Avatar answered Feb 17 '26 08:02

Evk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!