本文介绍了我能为dapper-dot-net映射指定DB列名吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法使用dapper-dot-net使用属性指定应该使用的列名,而不是属性名?

  public class Code 
{
public int Id {get;组; }
public string Type {get;组; }
//这在表中称为代码。
public string Value {get;组; }
public string描述{get;组; }
}

我想要命名我的属性。



如果没有dapper, >解决方案

您还可以查看。 p>

它有一个,您可以在其中指定自定义字段映射。例如:

  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);
}
}

那么你只需要:

 使用(SqlConnection cn = new SqlConnection(_connectionString))
{
cn.Open
var code = new Code {Type =Foo,Value =Bar};
int id = cn.Insert(code);
cn.Close();
}

请注意,您必须将自定义地图保留在同一程序集中POCO类。



更新






b

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

  DapperExtensions.SetMappingAssemblies(new [] { typeof(MyCustomClassMapper).Assembly}); 


Is there a way with dapper-dot-net to use an attribute to specify column names that should be used and not the property name?

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

I'd like to be able to name my properties whatever I choose. Our database has no consistent naming convention.

If not with dapper, are there any additional similar options?

解决方案

You can also check out Dapper-Extensions.

It has an auto class mapper, where you can specify your custom field mappings. For example:

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");
    }
}

Then you just do:

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

Keep in mind that you must keep your custom maps in the same assembly as your POCO classes. The library uses reflection to find custom maps and it only scans one assembly.

Update:

You can now use SetMappingAssemblies to register a list of assemblies to scan:

DapperExtensions.SetMappingAssemblies(new[] { typeof(MyCustomClassMapper).Assembly });

这篇关于我能为dapper-dot-net映射指定DB列名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 20:14