我可以为dapper-dot-net映射指定DB列名吗?

Wal*_*esh 22 c# database dapper

有没有办法使用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; }
}
Run Code Online (Sandbox Code Playgroud)

无论我选择什么,我都希望能够命名我的房产.我们的数据库没有一致的命名约定.

如果没有小巧玲珑,还有其他类似的选择吗?

Voi*_*Ray 26

您还可以查看 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

那你就做:

using (SqlConnection cn = new SqlConnection(_connectionString))
{
    cn.Open();
    var code= new Code{ Type = "Foo", Value = "Bar" };
    int id = cn.Insert(code);
    cn.Close();
}
Run Code Online (Sandbox Code Playgroud)

请记住,您必须将自定义地图与POCO类保持在同一个程序集中.该库使用反射来查找自定义地图,它只扫描一个程序集.

更新:

您现在可以使用SetMappingAssemblies注册要扫描的程序集列表:

DapperExtensions.SetMappingAssemblies(new[] { typeof(MyCustomClassMapper).Assembly });
Run Code Online (Sandbox Code Playgroud)


Ric*_*ick 20

如果直接使用select语句或在过程中使用,则只能对列进行别名.

SELECT code as Value FROM yourTable
Run Code Online (Sandbox Code Playgroud)