LINQ to SQL缓存问题

Gra*_*ell 4 c# caching linq-to-sql

长话短说:我正在使用Linq来进行sql,但是我的缓存存在问题

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

最后是ac#question(希望是我的一个基本错误).在下面的代码,如果我跑method1,然后method2doc2 == doc1(和我希望它从DB获得原始值)

这对我来说似乎很奇怪,因为RecordDictionary类是旋转数据(所以不直接与模型相关),在我的代码中,赋值在不同的控制器中; 但不知何故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;
} 
Run Code Online (Sandbox Code Playgroud)

Sim*_*han 6

每个"工作单元"创建一个新的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();
}
Run Code Online (Sandbox Code Playgroud)

您还可以在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);
}
Run Code Online (Sandbox Code Playgroud)