2013-03-05 70 views
0

我有一个与Azure SQL的MVC 4网站,他们表现很奇怪。当我在本地运行它时(IIS Express),我对我的数据库有一个LINQ查询,即使它发生更改也会返回相同的数据,并且我可以通过单独的查询查看它。我真的很想知道发生了什么事。LINQ不刷新数据

我使用的控制器功能是

public int GetNotificationTotalCount(int userId) 
    { 
     int cnt = 0; 
     var tmp = (from entry in _db.NotificationCounts 
        where entry.UserId == userId 
        select entry).FirstOrDefault(); 

     if (tmp != null) // return zeros 
      cnt = tmp.FlagsCount + tmp.RepliesCount; 

     return cnt; 
    } 

,其中_分贝是我的DataContext和LINQ返回的IQueryable

我知道它缓存数据,因为IQueriable但我正在退出此功能,tmp对象应该被销毁。或者我想。

是吗?

+0

你在测试什么浏览器?我发现有时IE会缓存数据,您需要将一个属性([CacheControl(HttpCacheability.NoCache),HttpGet])添加到您的方法中以防止出现这种情况。 – lopezbertoni 2013-03-06 00:50:27

+0

我在IE和Chrome中看到了这个问题。 – 2013-03-06 03:01:32

回答

1

我假设你的上下文寿命太长。 DataContext实例应该是短暂的。 entry对象被缓存进来,所以当你尝试从缓存中取出它时,除非你明确地刷新该对象。

public int GetNotificationTotalCount(int userId) 
{ 
    using(var db = new MyDataContext()) 
    { 
     return (from entry in db.NotificationCounts 
       where entry.UserId == userId 
       select entry.FlagsCount + entry.RepliesCount) 
       .FirstOrDefault() ?? 0; 
    } 
}