您还可以查看 Dapper-Extensions。
Dapper Extensions 是一个小型库,通过为您的 POCO 添加基本的 CRUD 操作(获取、插入、更新、删除)来补充 Dapper。
它有一个自动类映射器,您可以在其中指定自定义字段映射。例如:
public class CodeCustomMapper : ClassMapper<Code>
{
public CodeCustomMapper()
{
base.Table("Codes");
Map(f => f.Id).Key(KeyType.Identity);
Map(f => f.Type).Column("Type");
Map(f => f.Value).Column("Code");
Map(f => f.Description).Column("Foo");
}
}
然后,您只需执行以下操作:
using (SqlConnection cn = new SqlConnection(_connectionString))
{
cn.Open();
var code= new Code{ Type = "Foo", Value = "Bar" };
int id = cn.Insert(code);
cn.Close();
}
请记住,您必须将自定义地图保存在与 POCO 类相同的程序集中。该库使用反射来查找自定义地图,它只扫描一个程序集。
更新:
您现在可以使用 SetMappingAssemblies 注册要扫描的程序集列表:
DapperExtensions.SetMappingAssemblies(new[] { typeof(MyCustomClassMapper).Assembly });