我有
Dapper
模型,可与 ColumnAttributeTypeMapper
代码一起使用。
此属性有助于将 SQL 列名称映射到模型上的属性。
有一件事是,我需要告诉 Dapper 了解这个 Model 类,所以我需要为每个模型执行以下代码:
Dapper.SqlMapper.SetTypeMap(typeof(FooModel), new ColumnAttributeTypeMapper<FooModel>());
...
我尝试通过创建 IModel 接口来自动化此操作:
public interface IModel {}
并使用扩展查找所有实现 IModel 的类并映射它们:
public static class WebApplicationExtensions
{
public static void MapModels(this WebApplication app)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var classes = assemblies.Distinct().SelectMany(x => x.GetTypes())
.Where(x => typeof(IModel).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract);
foreach (var classe in classes)
{
Dapper.SqlMapper.SetTypeMap(classe, new ColumnAttributeTypeMapper<classe>());
}
}
}
app.MapModels();
但是构建抛出错误:
'classe' is a variable but is used like a type
。
我也尝试做以下事情:
Dapper.SqlMapper.SetTypeMap(typeof(classe), new ColumnAttributeTypeMapper<classe>());
Dapper.SqlMapper.SetTypeMap(typeof(classe), new ColumnAttributeTypeMapper<typeof(classe)>());
但也没有成功。如何让 dotnet 将这些模型“注册”到 Dapper?
像这样使用 Type.MakeGenericType:
foreach (var classe in classes)
{
Dapper.SqlMapper.SetTypeMap(classe, (ITypeMap?)Activator.CreateInstance(typeof(ColumnAttributeTypeMapper<>).MakeGenericType(classe)));
}