长话短说:我正在使用 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/