问题
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