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
        {}
    }
  • 相关阅读:
    多区域显示(5)-粘贴为图片链接
    coco2d-x怎样创建project
    把数组排成最小的数
    前端框架 EasyUI (1)熟悉一下EasyUI
    easyui form 方式提交数据
    Jquery插件easyUi表单验证提交
    EASYUI 表单(FORM)用法
    easyui form submit 不提交
    JQuery Easy Ui dataGrid 数据表格
    EasyUI datagrid 格式化显示数据
  • 原文地址:https://www.cnblogs.com/Zdelta/p/14122337.html
Copyright © 2011-2022 走看看