Entity framework does not refresh data

asp.net-core c# entity-framework-core

Question

I have a repository function as below:

public async Task<TableName> SomeFunction(int id)
{
  return await _context.TableName.FirstOrDefaultAsync(u => u.Id == id);
}

In my Controller, I am calling the above function as follows:

var data = await _repo.SomeFunction(id);
.....
.....
.....
.....
data = await _repo.SomeFunction(id);

The second time when I call the function back it does not give me updated data.

Note: There is a backend process which updates this data meanwhile and there is some criteria through which I land to the 2nd repeatation of the same function call.

1
-1
9/6/2019 1:07:52 PM

Accepted Answer

Try this way:

public async Task<TableName> SomeFunction(int id)
{
  return await _context.TableName.AsNoTracking().FirstOrDefaultAsync(u => u.Id == id);
}

The only downside is that the entity will not be added to the context.

1
9/6/2019 12:50:38 PM

Popular Answer

The context is created with a scoped lifetime, which for a web app would be the life of a request. During this time, any injection of your context will use the same instance. Internally, a DbContext has an object cache, which it fills with the results of your queries, so when you first request this entity, it's cached, and all future requests for the same entity, while that context instance lives, returns from the object cache instead of making the query to the database again. This is by design, and is desirable functionality. It greatly reduces the load on your database, and benefits the performance of both EF and your app.

If you really want to ensure that the data is always up to date, then you can do:

var refreshedEntity = _context.Entry(entity).GetDatabaseValues();

You can also just pull the entity out originally using AsNoTracking():

return await _context.TableName.AsNoTracking().FirstOrDefaultAsync(u => u.Id == id);

However, if you do that, you'll need to ensure it's attached to the context if you want to modify it and save it back. Returning a detached entity from a method like this is not going to be obvious to the consumer that it is detached, and could lead to exceptions.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow