namespaceyournamespace{/// <summary> ///Uses The Name value of the Columnattribute specified, otherwise maps as usual. /// </summary> /// <typeparam name= "T" >The type of the object is this mapper applies to.</typeparam> Public classColumnattributetypemapper<t>: fallbacktypemapper { Publiccolumnattributetypemapper ():Base(Newsqlmapper.itypemap[] {NewCustompropertytypemap (typeof(T), (type, columnName)=type. GetProperties (). FirstOrDefault (Prop=Prop. GetCustomAttributes (false) . OfType<ColumnMappingAttribute>() . Any (attr= = attr. Name = =columnName)) ), NewDefaulttypemap (typeof(T))}) {}} [AttributeUsage (Attributetargets.property, AllowMultiple=true)] Public classColumnmappingattribute:attribute { Public stringName {Get;Set; } } Public classFallbackTypeMapper:SqlMapper.ITypeMap {Private ReadOnlyIenumerable<sqlmapper.itypemap>_mappers; PublicFallbacktypemapper (ienumerable<sqlmapper.itypemap>mappers) {_mappers=mappers; } PublicConstructorInfo Findconstructor (string[] names, type[] types) { foreach(varMapperinch_mappers) { Try{constructorinfo result=Mapper. Findconstructor (names, types); if(Result! =NULL) { returnresult; } } Catch(notimplementedexception) {}}return NULL; } PublicSqlmapper.imembermap Getconstructorparameter (ConstructorInfo constructor,stringcolumnName) { foreach(varMapperinch_mappers) { Try { varresult =Mapper. Getconstructorparameter (constructor, ColumnName); if(Result! =NULL) { returnresult; } } Catch(notimplementedexception) {}}return NULL; } PublicSqlmapper.imembermap GetMember (stringcolumnName) { foreach(varMapperinch_mappers) { Try { varresult =Mapper. GetMember (ColumnName); if(Result! =NULL) { returnresult; } } Catch(notimplementedexception) {}}return NULL; } } }
Public Static IEnumerable loadwithcustommapping () { using (var conn = opendbconnection ()) { Dapper.SqlMapper.SetTypeMap (typeofnew columnattributetypemapper ()); return Conn. Query ("select TOP caid,caname,en from Cityarea");} }
Dapper custom database fields and code mapping method when the model field is inconsistent