Reputation: 339
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.
Upvotes: 0
Views: 2439
Reputation: 239220
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.
Upvotes: 2
Reputation: 84
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.
Upvotes: 2