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

泪湿孤枕 提交于 2019-12-03 01:23:26

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

If you are using a select statement directly or in a procedure you can just alias the columns.

SELECT code as Value FROM yourTable

Another approach is to just manually map it with the dynamic result.

var codes = conn.Query<dynamic>(...sql and params here...)
                 .Select<dynamic,Code>(s=>new Code{Id = s.Id, Type = s.Type, Value = s.code, Description = s.Description});

Clearly this introduces type-safety scenarios because you are querying on dynamic. Also, you have to manually map columns which is a bummer.

However, I tend to like this approach because it's so darned transparent. You can cast if need be (as is the case with Enums), and basically just do whatever it is you need to do to go from the db recordset to your properties.

For selects, you can add constructors to your classes to perform the mapping. The constructor parameter names must match the table columns.

Below is an example from the source. The table will be correctly mapped to the class.

Table:

CREATE TABLE #Users (Id int, Name varchar(20))

Class:

   class UserWithConstructor
    {
        public UserWithConstructor(int id, string name)
        {
            Ident = id;
            FullName = name;
        }
        public int Ident { get; set; }
        public string FullName { get; set; }
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!