今天在網上看到使用字典結構建立 數據庫字段和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
{}
}