NET[C#]Dapper中数据表的字段(列)与实体属性不一致时,如何手动配置它们之间的映射?

问题描述

比如有如下的数据表结构:
Person:

person_id  int
first_name varchar(50)
last_name varchar(50)

以及实体类:
Person:

public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

在C#程序中,使用Dapper做查询时,如何配置数据表字段(列)和实体类属性之间的映射呢?

方案一

var sql = @"select top 1 person_id PersonId, first_name FirstName, last_name LastName from Person";
using (var conn = ConnectionFactory.GetConnection())
{
var person = conn.Query<Person>(sql).ToList();
return person;
}

方案二

使用 ColumnAttribute 属性
完整的代码片段:

namespace YourNamespace
{
/// <summary>
/// Uses the Name value of the <see cref="ColumnAttribute"/> specified to determine
/// the association between the name of the column in the query results and the member to
/// which it will be extracted. If no column mapping is present all members are mapped as
/// usual.
/// </summary>
/// <typeparam name="T">The type of the object that this association between the mapper applies to.</typeparam>
public class ColumnAttributeTypeMapper<T> : FallbackTypeMapper
{
public ColumnAttributeTypeMapper()
: base(new SqlMapper.ITypeMap[]
{
new CustomPropertyTypeMap(
typeof(T),
(type, columnName) =>
type.GetProperties().FirstOrDefault(prop =>
prop.GetCustomAttributes(false)
.OfType<ColumnAttribute>()
.Any(attr => attr.Name == columnName)
)
),
new DefaultTypeMap(typeof(T))
})
{
}
} [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class ColumnAttribute : Attribute
{
public string Name { get; set; }
} public class FallbackTypeMapper : SqlMapper.ITypeMap
{
private readonly IEnumerable<SqlMapper.ITypeMap> _mappers; public FallbackTypeMapper(IEnumerable<SqlMapper.ITypeMap> mappers)
{
_mappers = mappers;
} public ConstructorInfo FindConstructor(string[] names, Type[] types)
{
foreach (var mapper in _mappers)
{
try
{
ConstructorInfo result = mapper.FindConstructor(names, types);
if (result != null)
{
return result;
}
}
catch (NotImplementedException)
{
}
}
return null;
} public SqlMapper.IMemberMap GetConstructorParameter(ConstructorInfo constructor, string columnName)
{
foreach (var mapper in _mappers)
{
try
{
var result = mapper.GetConstructorParameter(constructor, columnName);
if (result != null)
{
return result;
}
}
catch (NotImplementedException)
{
}
}
return null;
} public SqlMapper.IMemberMap GetMember(string columnName)
{
foreach (var mapper in _mappers)
{
try
{
var result = mapper.GetMember(columnName);
if (result != null)
{
return result;
}
}
catch (NotImplementedException)
{
}
}
return null;
} public ConstructorInfo FindExplicitConstructor()
{
return _mappers
.Select(mapper => mapper.FindExplicitConstructor())
.FirstOrDefault(result => result != null);
}
} }

调用方法:

public class Person
{
[Column(Name="person_id")]
public int PersonId { get; set; }
[Column(Name="first_name")]
public string FirstName { get; set; }
[Column(Name="last_name")]
public string LastName { get; set; }
}

方案三

使用 CustomPropertyTypeMap 自定义属性类型映射类,如:

public class ColumnMap
{
private readonly Dictionary<string, string> forward = new Dictionary<string, string>();
private readonly Dictionary<string, string> reverse = new Dictionary<string, string>(); public void Add(string t1, string t2)
{
forward.Add(t1, t2);
reverse.Add(t2, t1);
} public string this[string index]
{
get
{
// Check for a custom column map.
if (forward.ContainsKey(index))
return forward[index];
if (reverse.ContainsKey(index))
return reverse[index]; // If no custom mapping exists, return the value passed in.
return index;
}
}
}

配置列映射关系

var columnMap = new ColumnMap();
columnMap.Add("Field1", "Column1");
columnMap.Add("Field2", "Column2");
columnMap.Add("Field3", "Column3"); SqlMapper.SetTypeMap(typeof (MyClass), new CustomPropertyTypeMap(typeof (MyClass), (type, columnName) => type.GetProperty(columnMap[columnName])));

方案四

查询时使用LINQ

 var sql = @"select top 1 person_id, first_name, last_name from Person";
using (var conn = ConnectionFactory.GetConnection())
{
List<Person> person = conn.Query<dynamic>(sql)
.Select(item => new Person()
{
PersonId = item.person_id,
FirstName = item.first_name,
LastName = item.last_name
}
.ToList(); return person;
}
http://2sharings.com/2018/dapper-orm-manually-map-column-names-with-class-properties-in-csharp-application

Dapper中数据表的字段(列)与实体属性不一致时,如何手动配置它们之间的映射?的更多相关文章

  1. MySql中数据表增加字段很慢怎么办

    正确的做法是这样,对于数据量很大的表,需要添加所有或者修改字段的做法是如下: 1.先创建一张一样的表 create table new_tb like tb_old; 2.修改创建表的字段 alter ...

  2. c++中数据表如何转成业务实体--map和结构体的相互转换

    应用场景:如何把数据库表中的一行转换成一个业务实体结构体,c#和java中都有实体框架,表到实体的转换很方便,c++中缺少这些框架,但是有一些折中的办法去做.其实问题的本质是:map如何转成结构体. ...

  3. PHP获取mysql数据表的字段名称及详细属性

    SHOW DATABASES //列出 MySQL Server 数据库. SHOW TABLES [FROM db_name] //列出数据库数据表. SHOW CREATE TABLES tbl_ ...

  4. 给MySQL中数据表添加字段

    添加一个char字段: mysql> alter table stock add src char(20); Query OK, 3766 rows affected (0.65 sec) Re ...

  5. mysql中通过sql语句查询指定数据表的字段信息

      mysql数据库在安装完成时,自动创建了information_schema.mysql.test这三个数据库.其中,information_schema记录了创建的所有数据库的相关信息,因此可以 ...

  6. 使用sql查询mysql/oracle/sql server/gp数据库中指定表的字段信息(字段名/字段类型/字段长度/是否是主键/是否为空)

    1,根据数据库类型拼接不同URL /** * 根据类型不同拼接连接的URL * @param dbType 1:mysql.2:oracle.3:sql server.4:gp * @param ip ...

  7. 第二百七十七节,MySQL数据库-数据表、以及列的增删改查

    MySQL数据库-数据表.以及列的增删改查 1.创建一个表 CREATE(创建) TABLE(表) ENGINE(引擎) ENGINE=INNODB(引擎)还有很多类引擎,这里只是简单的提一下INNO ...

  8. MySQL中数据表的基本操纵

    本文基于对国家863中部软件孵化器编著的<MySQL从入门到精通>一书的操作实践.  一.创建数据表 数据表属于数据库,在创建数据表之前,应该使用语句 USE 数据库名  指定操作是在那个 ...

  9. Java对比两个数据库中的表和字段,写个冷门的东西

    Java对比两个数据库中的表和字段,写个冷门的东西 转载的 来源网络 目前所在的项目组距离下个版本上线已经很近了,就面临了一个问题:开发人员在开发库上根据需要增加数据表.数据字段.或者变更了字段类型或 ...

随机推荐

  1. 安卓代码迁移:Make.exe: *** [libs/armabi-v7a/gdbserver] Error 1

    解决办法1:安装ndk和eclipse修改为x86操作系统 解决办法2:降低更换NDK版本

  2. (转)C#开发微信门户及应用(4)--关注用户列表及详细信息管理

    http://www.cnblogs.com/wuhuacong/p/3695213.html 在上个月的对C#开发微信门户及应用做了介绍,写过了几篇的随笔进行分享,由于时间关系,间隔了一段时间没有继 ...

  3. 数据清理,预处理 pandas dataframe 操作技巧 总结

    dsoft2 = data1.loc[(data1['程'] == "轻") | (data1['程'] == "中")]设置x下标plt.xticks(np. ...

  4. PAT_A1126#Eulerian Path

    Source: PAT A1126 Eulerian Path (25 分) Description: In graph theory, an Eulerian path is a path in a ...

  5. Firefly-rk3399 开发板环境搭建

    Firefly教程网站:http://wiki.t-firefly.com/zh_CN/Firefly-RK3399/started.html 系统烧录: http://wiki.t-firefly. ...

  6. Ubuntu14.043下QT5.5的安装与一点问题

    请注明来自于 http://www.cnblogs.com/usegear/p/5100720.html 1.下载qt-opensource-linux-x86-5.5.0.run(去教育镜像网站下载 ...

  7. Web Service 附件技术的发展及演变

    Web Service 通常将业务数据封装在 SOAP 主体或者 SOAP 消息附件中进行传输,这些附件往往采用 Base64 编码二进制方式进行封装,这将大大增加待传输的数据量,消耗比较长的编码时间 ...

  8. 0804关于mysql 索引自动优化机制: 索引选择性(Cardinality:索引基数)

    转自http://blog.csdn.net/zheng0518/article/details/50561761 1.两个同样结构的语句一个没有用到索引的问题: 查1到20号的就不用索引,查1到5号 ...

  9. i386和x86-64区别通俗易懂版本(转)

    x86架构首度出现在1978年推出的Intel 8086中央处理器,它是从Intel 8008处理器中发展而来的,而8008则是发展自Intel 4004的.Intel之后又推出了包括80186.80 ...

  10. Linux中tty是什么(tty1~7)

    tty:终端设备的统称. tty一词源于Teletypes,或者teletypewriters,原来指的是电传打字机,是通过串行线用打印机键盘通过阅读和发送信息的东西,后来这东西被键盘与显示器取代,所 ...