dapper-dot-net 有没有办法使用属性来指定应该使用的列名称而不是属性名称?
public class Code
{
public int Id { get; set; }
public string Type { get; set; }
// This is called code in the table.
public string Value { get; set; }
public string Description { get; set; }
}
我希望能够为我的属性命名,无论我选择什么。我们的数据库没有一致的命名约定。
如果没有 dapper,还有其他类似的选项吗?
您还可以查看简洁的扩展 https://github.com/tmsmith/Dapper-Extensions.
Dapper Extensions 是一个小型库,通过添加
POCO 的基本 CRUD 操作(获取、插入、更新、删除)。
它有一个自动类映射器 https://github.com/tmsmith/Dapper-Extensions/wiki/AutoClassMapper,您可以在其中指定自定义字段映射。例如:
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 类保存在同一程序集中。该库使用反射来查找自定义映射,并且仅扫描一个程序集。
Update:
您现在可以使用 SetMappingAssemblies 注册要扫描的程序集列表:
DapperExtensions.SetMappingAssemblies(new[] { typeof(MyCustomClassMapper).Assembly });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)