Entity Framework lazy loading with AsNoTracking()

2019-04-28 03:14发布

We are currently using lazy loading for Entity Framework and running into out of memory exception. The reason why we're running into this exception is because the Linq query loads a lot of data and at latter stages it's using lazy loading to load navigation properties. But because we don't use NoTrackingChanges Entity Framework cache builds up really quickly which results in out of memory error.

My understanding with EF is the we should always use NoTrackingChanges on query unless you want to update the returned object from the query.

I then tested using NoChangeTracking:

var account = _dbcontext.Account
                        .AsNoTracking()
                        .SingleOrDefault(m => m.id == 1); 
var contactName = account.Contact.Name

but I get the following error:

System.InvalidOperationException: When an object is returned with a NoTracking merge option, Load can only be called when the EntityCollection or EntityReference does not contain objects.

1条回答
等我变得足够好
2楼-- · 2019-04-28 04:03

You've specified for EF to not track your instantiated Account value:

var account = _dbcontext.Account.AsNoTracking().SingleOrDefault(m=>m.id == 1);

Thus trying to access navigation properties off of them will never work:

var contactName = account.Contact.Name

You can explicitly include navigation properties you want by using the Include(). So the following should work:

var account = _dbcontext.Account
  .Include(a => a.Contact)
  .AsNoTracking()
  .SingleOrDefault(m=>m.id == 1);

var contactName = account.Contact.Name;  // no exception, it's already loaded
查看更多
登录 后发表回答