c# - LINQ to SQL 缓存问题

标签 c# linq-to-sql caching

长话短说:我正在使用 Linq to sql,但它的缓存有问题

我的应用程序是元数据驱动的,所以我不想缓存(数据库中的更改应该在页面刷新时反射(reflect)在网站上)。有没有办法关闭缓存?或重置缓存的方法(例如,当前当我更改数据库中的数据时,我必须物理更改代码并重新编译才能看到结果)。

最后是一个 c# 问题(希望是我的基本错误)。 在下面的代码中,如果我运行 method1 然后 method2 然后 doc2 == doc1 (我希望它从数据库中获取原始值)

这对我来说似乎很奇怪,因为 RecordDictionary 类是旋转数据(因此与模型没有直接关系),并且在我的代码中,分配在不同的 Controller 中;但不知何故,linq to sql 正在缓存应用于 doc1 的更改并将它们应用于 doc2(如果我退出我的应用程序,然后重新编译 doc2等于我期望的值(直到我更改 doc1)

人为的例子

public RecordDictionary method1()
{
    RecordDictionary doc1 = genericRepository.GetRecordById(
        action.AppliesToModelEntityId, 27);

    //do some stuff to doc1 here
    return doc1;
}

public RecordDictionary method2()
{    
    RecordDictionary doc2 = genericRepository.GetRecordById(
        action.AppliesToModelEntityId, 27);
    return doc2;
}

public RecordDictionary GetRecordById(int ContainerModelId, int id)
{
    var query = (from dv in _db.DataValues
                 where dv.DataInstance.IsCurrent == true &&
                     dv.DataInstance.DataContainer.DataContainerId == id
                 select new { 
                     dv.DataInstance.DataContainer.ParentDataContainerId, 
                     dv });

    RecordDictionary result = CreateRecordColumns(
        ContainerModelId, query.FirstOrDefault().ParentDataContainerId);
    result.Id = id;

    foreach (var item in query)
    {
        if (result.ContainsKey(item.dv.ModelEntity.ModelEntityId))
            result[item.dv.ModelEntity.ModelEntityId] = item.dv;                               
    }

    return result;
} 

最佳答案

为每个“工作单元”创建一个新的 DataContext:即一个 HTTP 请求,甚至一个方法 [1] - 目的是在方法结束时(或作为实现的一部分)调用一次 SubmitChanges。

// Where this is all one (financial) transaction.
void Transfer(int fromAccountId, int toAccountId, decimal amount) {
    var db = new Customers();
    var fromAccount = db.Accounts.Single(row => row.Id == fromAccountId);
    var toAccount = db.Accounts.Single(row => row.Id == toAccountId);
    fromAccount.Balance -= amount;
    toAccount.Balance += amount;
    db.SubmitChanges();
}

您还可以在您希望在 DataContexts 后面更改的行上调用 DataContext.Refresh(),但很难有效地使用它。它适用于存储过程之类的东西:

var client = db.Clients.Single(row => row.Id == clientId);
if (!client.CheckingAccount) {
    db.CreateCheckingAccount(client.Id); // Stored procedure.
    db.Refresh(RefreshMode.OverwriteCurrentValues, client);
}

关于c# - LINQ to SQL 缓存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2011019/

相关文章:

c# - 如何使用 Linq "NOT IN"

c# - asp.net c# 中 session 变量范围的范围是什么?

c# - 如何在 C# 中从 Redis 数据库获取、更新所有键及其值?

html - 为什么包含 "apple-mobile-web-app-capable"标记会破坏我的网络应用程序在 iOS 上的离线功能?

language-agnostic - 99.9%的数据频繁更改时要缓存什么?

c# - Linq 到 XML : Queries for If blocks C#

c# - DetailsView 不会进入编辑模式

linq-to-sql - SqlMetal 不生成 View 、函数或存储过程

c# - 如何将 linq 中的两列连接到 sql 查询的选择投影

asp.net-mvc - 无法使用InsertOnSubmit()插入新的Employee实体