Dapper数据表字段(列)与实体属性,dictionary手动映射

本文介绍了如何使用Dapper通过字典结构实现数据库表字段与.NET Core实体属性的手动映射。在面对字段名称不一致的情况时,提供了一种解决方案,即创建映射类并注册映射关系,确保数据正确转换。此外,当模型名称与数据库表名不匹配时,可以通过在模型类上添加[Table("表名")]特性来解决。

今天在网上看到使用字典结构建立 数据库字段和model属性的方法;

接上一篇:

https://blog.youkuaiyun.com/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
    {}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值