Is there a way to map properties to column names using some .Insert extension method for Dapper?

邮差的信 提交于 2020-04-17 08:42:24

问题


I have the following challenge with this class:

Public Class MyClass
    Property Id As Integer
    Property LastName as String
End Class

The corresponding data table in the database has as fields: Id (int, not null) Last-Name (nvarchar(80),null)

So I need to map MyClass.LastName to MyClasses.Last-Name and have a hell of a time...

When I write a custom Insert query it all works, but I would like to use the .Insert statement of one of the Dapper extensions packages.

I tried Dapper.Contrib, but this ignores mappings that I create using Dapper.FluentMap or using the built in method of Dapper itself using Dapper.SetTypeMap.

I tried Dapper.FastCrud, but I was unable to figure out how to configure mappings for it, though this API seems promising.

Anyone?


回答1:


So, basically the problem here is that the property name and column name is different.

With Dapper, you can handle this by providing alias for column name in SQL query. I guess you have already tried this as you said "I write a custom Insert query" in your question. Other multiple ways to map column names with properties are discussed here.

With DapperExtensions, you can map the different column names with their respective properties something like below:

public sealed class MyClassMapper : ClassMapper<MyClass>
{
    public MyClassMapper()
    {
        Table("MyTable");
        Map(x => x.Id).Key(KeyType.WhatYouWant);
        Map(x => x.LastName).Column("Last-Name");
        AutoMap();
    }
}

Code sample is with C#. You have to translate it to VB.NET.

With Dapper.Contrib, you can decorate the class with [Table] attribute to map the table name. Alternatively, you can use SqlMapperExtensions.TableNameMapper to map the tables. Please refer to this blog post or this and this and this SO posts for more details.
Apparently, there is no way to map the column name. This feature is planned for next major (2.x) version.

With Dapper.FastCrud, there are multiple ways for mapping. You can decorate the property with [Column] attribute.



来源:https://stackoverflow.com/questions/48407241/is-there-a-way-to-map-properties-to-column-names-using-some-insert-extension-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!