zoukankan      html  css  js  c++  java
  • 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
        {}
    }
  • 相关阅读:
    Java集合和数组的区别
    二分法查找
    功能模块划分的原则及方法
    CentOS 6.5 开机启动指定服务
    CentOS 6.5配置mysql
    CentOS 6.5安装Tcpreplay
    CentOS6.5 常用命令
    CentOS6.5 安装ntopng-1.2.0
    【转】CentOS安装PF_RING(虚拟机)
    CentOS查询 杀死进程
  • 原文地址:https://www.cnblogs.com/Zdelta/p/14122337.html
Copyright © 2011-2022 走看看