LINQ to SQL实体身份缓存和已编译查询错误的解决方法? [英] Workaround for LINQ to SQL Entity Identity Caching and Compiled Query Bug?

查看:100
本文介绍了LINQ to SQL实体身份缓存和已编译查询错误的解决方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了linq to sql中的一个错误,在已编译查询中执行主键查询时,身份缓存不起作用.

I've come across what appears to be a bug in linq to sql where identity caching does not work when performing primary key queries inside of a compiled query.

我写了以下示例来演示身份缓存的用法.它只会在第一次命中数据库时执行一次调用,此后每次都会从数据上下文的缓存中检索客户实体.

I wrote the following sample to demonstrate the usage of identity caching. It only executes one call to the database the first time it's hit, every time after that it retrieves the customer entity from the data context's cache.

    for(int i=0; i<10; i++)
    {
        DataContext.GetTable<Customer>().Single(c=>c.Id == 1);
    }

不幸的是,当我将上述示例转换为编译查询时,它无法利用身份高速缓存,实际上对数据库执行了10次调用.

Unfortunately, when I convert the above sample to a compiled query, it fails to utilize the identity cache and actually executes 10 calls to the database.

    for(int i=0; i<10; i++)
    {
        RetrieveCustomer(DataContext, 1);
    }

    private static readonly Func<DataContext, int, Customer> RetrieveCustomer =
    CompiledQuery.Compile((DataContext context, int id) => context.GetTable<Customer>().Single(c=>c.Id == id));

是否还有其他人遇到此问题并创建了解决方法?对于基于服务器的应用程序来说,利用编译查询和身份缓存非常重要,因此我希望这是其他人以前解决过的问题!

Has anyone else come across this problem and created a workaround for it? It is extremely important for server based applications to utilize compiled queries and identity caching, so I'm hoping this is a problem that someone else has worked through before!

推荐答案

我最终使用了肮脏的技巧来解决此问题,方法是使用反射调用称为GetCachedEntity的linq实体对象的私有方法来强制利用缓存.我没有时间实施更干净的解决方案,但是对于对此主题感兴趣的任何人,我建议您针对这种情况实施自己的缓存机制.

I ended up using a dirty hack to workaround this by using reflection to call a private method of linq entity objects called GetCachedEntity to forcefully utilize the cache. I didn't have time to implement a cleaner solution but for anyone interested in this topic I would recommend implementing your own caching mechanism for this scenario.

这篇关于LINQ to SQL实体身份缓存和已编译查询错误的解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆