繁体   English   中英

LINQ to SQL缓存问题

[英]LINQ to SQL cache issues

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

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

最后是ac#question(希望是我的一个基本错误)。 在下面的代码中,如果我运行method1然后是method2那么doc2 == doc1 (我希望它从db获取原始值)

这对我来说似乎很奇怪,因为RecordDictionary类是数据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;
} 

每个“工作单元”创建一个新的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);
}

ObjectTrackingEnabled是否在您的数据上下文类中设置为true? 如果是这样,您可能想尝试将其设置为false。 此外,您可能会发现阅读此博客条目很有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM