gpt4 book ai didi

c# - 为 Dapper 重置缓存

转载 作者:太空狗 更新时间:2023-10-29 18:32:25 26 4
gpt4 key购买 nike

有没有办法重置缓存 Dapper产生?我在我的数据库中删除了一个表列,然后收到错误“找不到列”。我重置了 IIS,之后一切正常。

这可以在不重新启动 IIS 的情况下重置吗?谢谢。

最佳答案

更新 2018-02-08

自从大约 5 年前编写此答案以来,Dapper 代码发生了很大变化。正如 Marc Gravell 对这个问题的评论,在提出问题时本不应该需要这个,所以它在今天可能也没有多大用处。

代码可能不再有效,也可能不再有效。即使它仍然有效,它也不是最佳的,所以我不能真诚地推荐它。使用风险自负。


Database.cs 的第 227 行显示:

static ConcurrentDictionary<Type, string> tableNameMap = new ConcurrentDictionary<Type, string>();
static ConcurrentDictionary<Type, List<string>> paramNameCache = new ConcurrentDictionary<Type, List<string>>();

这意味着它是私有(private)的。我什至不确定您是否能够通过 Reflection 访问它(尽管值得一试)。最好的办法是向源代码添加一个 ClearCache 方法(因为它是开源的)并提交以供审核。

也许 Sam Saffron 或 Marc Gravell 可以详细说明。


我不使用 Dapper,但我认为以下扩展方法应该适用于 Repo 中的版本:

public static class DapperExtensions
{
public static void ClearTableCache<TDatabase>(this Database<TDatabase> dapperDb)
{
var fld = dapperDb.GetType().GetField("tableNameMap", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
if (fld == null)
throw new NotSupportedException("Unable to locate Private field tableNameMap");

var obj = fld.GetValue(null);
if (obj == null)
throw new NotSupportedException("Unable to get value from tableNameMap");

var clear = obj.GetType().GetMethod("Clear");
if (clear == null)
throw new NotSupportedException("Unable to locate ConcurrentDictionary<T, U>.Clear");

clear.Invoke(obj, null);
}
public static void ClearParamCache<TDatabase>(this Database<TDatabase> dapperDb)
{
var fld = dapperDb.GetType().GetField("paramNameCache", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
if (fld == null)
throw new NotSupportedException("Unable to locate Private field paramNameMap");

var obj = fld.GetValue(null);
if (obj == null)
throw new NotSupportedException("Unable to get value from paramNameMap");

var clear = obj.GetType().GetMethod("Clear");
if (clear == null)
throw new NotSupportedException("Unable to locate ConcurrentDictionary<T, U>.Clear");

clear.Invoke(obj, null);
}
}

尚未使用 Dapper 进行测试,但我使用 POCO 测试了原理。访问私有(private) API 是危险的(充其量),但此代码示例中使用的反射应该适用于当前版本。

关于c# - 为 Dapper 重置缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9612213/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com