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,是否还有其他类似的选项?
最佳答案
您还可以查看 Dapper-Extensions .
Dapper Extensions is a small library that complements Dapper by adding basic CRUD operations (Get, Insert, Update, Delete) for your POCOs.
它有一个 auto class mapper ,您可以在其中指定自定义字段映射。例如:
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();
}
请记住,您必须将自定义 map 保存在与 POCO 类相同的程序集中。该库使用反射来查找自定义映射,并且它只扫描一个程序集。
更新:
您现在可以使用 SetMappingAssemblies 来注册要扫描的程序集列表:
DapperExtensions.SetMappingAssemblies(new[] { typeof(MyCustomClassMapper).Assembly });
关于c# - 我可以为 dapper-dot-net 映射指定数据库列名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12183310/