EntityFramework - 刷新我的上下文以检查数据库更改

时间:2015-09-30 16:38:21

标签: asp.net entity-framework

我有一个Web.API工作正常,直到我在db中直接修改某些内容,并且API返回旧值,因为它没有刷新。

示例:

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;

它返回一个JSON:

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

如果我去数据库,并更新一个字段:

update tinvite set type = 1 where idInvite = 374

如何在不重新启动IIS的情况下使API返回类型= 1?

更新

我的上下文如下:

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

当我使用SQL Server Profiler实时检查数据库查询时,我发现EF在我的情况下进行了正确的查询:

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

应返回type = 1,但dataContext.Invites对象已经具有type(0)的旧值...

如果忽略其结果并使用上下文值

,为什么要进行此查询?

1 个答案:

答案 0 :(得分:1)

如果您不想将实体存储在本地上下文存储中,可以使用AsNoTracking()扩展方法:

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