nano
nano

Reputation: 2521

EntityFramework - Refresh my context to check DB changes

I've a Web.API working fine, until I modify something directly in the db, and the API returns the old value because it's not refreshed.

Example:

public class MyRepository {
    private static MyContext dataContext = new MyContext();
    public static List<Invite> GetAllInvitesByUser(string UserID) {
        ...
        IEnumerable<TInvite> results = 
            from i in dataContext.Invites
            where ...
            select i;

It returns a JSON:

{
    "invite": 
    {
        "idInvite": 374,
        "message": "hi there",
        "type": 0,
        ...

If I go the database, and update one field:

update tinvite set type = 1 where idInvite = 374

How can I make the API return type=1 without restarting the IIS?

UPDATE

My context looks like this:

public MyContext() :
        base("MyEntities")
{
    Configuration.ProxyCreationEnabled = false;
    Configuration.LazyLoadingEnabled = false;
}

When I check in real time the database queries with SQL Server Profiler, I see that EF makes the right query, in my case:

exec sp_executesql N'SELECT 
[Extent1].[idInvite] AS [idInvite], 
[Extent1].[message] AS [message], 
[Extent1].[type] AS [type], 
...
FROM [dbo].[TInvite] AS [Extent1]
WHERE ... 

which should return type = 1, but the dataContext.Invites object already has the old value for type (0)...

Why is it making this query if it's ignoring its result and using the context values??

Upvotes: 1

Views: 284

Answers (1)

Andrei
Andrei

Reputation: 44600

If you don't want to store your entities in local context storage, you can use AsNoTracking() extension method:

context.Invites.AsNoTracking().Where(...);

Upvotes: 1

Related Questions