Dapper数据表字段(列)与实体属性,dictionary手动映射
今天在网上看到使用字典结构建立 数据库字段和model属性的方法;
接上一篇:
https://blog.csdn.net/Zdelta/article/details/87636491
表book:
create_time datatime
类book
public class Book
{
public Datetime CreateTime;
}
要将这两个不同名的字段映射起来,可以添加以下类:
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("CreateTime", "create_time");
//其他字段同理
SqlMapper.SetTypeMap(typeof (Book), new CustomPropertyTypeMap(typeof (Book), (type, "create_time") => type.GetProperty(columnMap[ "create_time"])));
就是每次取字段的时候,手动翻译成对应的属性,这样也可以;
补充:
当model名与数据库表明不对应的时候,可以在model类引入dapper命名空间;
然后给model添加[Table("表明")],如:
using System;
using Dapper;
namespace namespace.Models
{
//建立model和table的映射
[Table("book")]
public class ReadBooks
{}
}