c# - 我可以为 dapper-dot-net 映射指定数据库列名吗?

标签 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; }
}

我希望能够随意命名我的属性。我们的数据库没有一致的命名约定。

如果不使用 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/

相关文章:

php - 如何在 PHP 和 MySQL 中合并 2 个表?

android - ContentValues 数组中的重复 ContentValues

c# - 高级级联删除

c# - Npgsql 3.0.0 解析枚举类型失败

c# - Dapper 参数未被替换

c# - 如何为服务引用指定 Web 代理?

c# - 许多 IF 语句与委托(delegate)?

c# - 如何增加 ASP.NET 标签中显示的文本中的行间距?

c# - RegEx 帮助匹配运算符

mysql - 在这种情况下如何在 SQL 中使用 GROUP BY 和 COUNT