Can I specify DB column names for dapper-dot-net mappings?

后端 未结 4 667
别跟我提以往
别跟我提以往 2021-02-05 05:04

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          


        
4条回答
  •  情话喂你
    2021-02-05 05:42

    You can also check out Dapper-Extensions.

    Dapper Extensions is a small library that complements Dapper by adding basic CRUD operations (Get, Insert, Update, Delete) for your POCOs.

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

    public class CodeCustomMapper : ClassMapper
    {
        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 });
    

提交回复
热议问题