0

我正在使用 Linq 查询从使用实体框架的 SQL 服务器中检索实体。当我更新实体时,EF 正在缓存结果。我怀疑这是因为 ObjectContext 在静态变量中(如下)。使用下面的代码刷新数据的唯一方法是调用一个方法并设置为何_dbnull显示可能显示过时的数据(例如:在 GridView 中)。有没有办法阻止它缓存,或者添加某种结束请求处理程序来在我的数据层上调用此方法,而不是需要检测何时可能显示陈旧数据?

private static ServiceEntities _db;
protected static ServiceEntitiesDb
    {
        get
        {
            if (_db == null)
            {
                _db = new ServiceEntities();
                _db.Contacts.MergeOption = MergeOption.OverwriteChanges; // failed
            }
            return _db;
        }
    }

    public static IEnumerable<Contact> GetContactsByName(string name) {
        var items = Db.Contacts;
        var filteredName = items.Where(i => (i.Name??string.Empty).IndexOf(name) >=0);
        return filteredName;
    }
4

1 回答 1

0

稍微冗长的解决方案(我想避免)是将其包装在 using 块中。IE:

public static IEnumerable<Contact> GetContactsByName(string name) {
        var items = Db.Contacts;
        var filteredName = items.Where(i => (i.Name??string.Empty).IndexOf(name) >=0);
        return filteredName;
}

变成

public static IEnumerable<Contact> GetContactsByName(string name) {
    using (var db = new SomeContext()) {
        var items = db.Contacts;
        var filteredName = items.Where(i => (i.Name??string.Empty).IndexOf(name) >=0);
        return filteredName;
    }
}
于 2012-07-12T08:20:06.840 回答