c# - 如何将数据库表列映射到 Dapper .Net 中的类属性

标签 c# .net sql-server asp.net-mvc-3 dapper

我有一个名为 employee 的表,并且有多个列,例如 EmpID,FirstName,MiddleName,LastName,Address,EmailID,RegionID,DesgID 我正在使用 Dapper .Net和处理 SQL Server 数据库的扩展。我使用 Dapper SqlExtensions 来插入、更新、删除功能,并使用 Dapper multimapper 选项来填充细节。所以我在上面的 employee 表中使用了下面的类

    [Table("employee")] //To map the table to class
    public class EmployeeModel
    {
        [Key] //Denote primary key
        public Int32 EmpID { get; set; }
        [Column("FirstName")] //Trying to map table column FirstName to variable First (Fails)
        public string First { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string EmailID { get; set; }
        public Int32 RegionID { get; set; }
        public RegionModel Region { get; set; }
        public DesignationModel Designation { get; set; }
        public Int32 DesgID { get; set; }

        public Int32 Add(EmployeeModel Details)
        {
            try
            {
                using (var connection = DBProviderFactory.GetOpenConnection()) //Creating IDbConnection Here
                {
                    return Convert.ToInt32(connection.Insert(Details)); //Using Dapper Extension To Insert New Employee Details
                }
            }
            catch (Exception ex)
            {
                return -1;
            }
        }

        public Int32 Update(EmployeeModel Details)
        {
            try
            {
                using (var connection = DBProviderFactory.GetOpenConnection())
                {
                    return Convert.ToInt32(connection.Update(Details)); //Using Dapper Extension to Update Employee Details
                }
            }
            catch (Exception ex)
            {
                return -1;
            }
        }



        public IEnumerable<EmployeeModel> AllEmployees()
        {
            try
            {
                using (var connection = DBProviderFactory.GetOpenConnection())
                {
                    //Using multi mapper in Dapper to Fill All Employee Details such as region,state,country,designation details etc..
                    string query = @"select e.EmpID,e.FirstName,e.MiddleName,e.LastName,e.Address,e.EmailID
                                     ,r.RegionID as RID,r.Region,s.StateID,s.State,c.CountryID,c.Country,d.DesgID as DID,d.Designation
                                       from employee as e inner join region as r on e.RegionID=r.RegionID
                                           inner join state as s on r.StateID=s.StateID inner join country as c on 
                                               s.CountryID=c.CountryID inner join designation as d on e.DesgID=d.DesgID";
                    return connection.Query<EmployeeModel, RegionModel, StateModel, CountryModel,DesignationModel, EmployeeModel>(query,
                        (employee, region, state, country, designation) =>
                        {
                            employee.Region = region;
                            region.State = state;
                            state.Country = country;
                            employee.Designation = designation;
                            return employee;
                        }, splitOn: "RID,StateID,CountryID,DID");
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

    }

    public class EmployeeModelMapper : ClassMapper<EmployeeModel>
    {
        public EmployeeModelMapper()
        {
            Map(m => m.Region).Ignore();
            Map(m => m.Designation).Ignore();
            Map(m => m.First).Column("FirstName"); //Trying to map table column FirstName to variable First (Fails in the case of Multimapping)
            AutoMap();
        }
    }

在上面的示例中,我尝试将表列 FirstName 映射到类变量 First 但在使用 Dapper connection 运行查询的情况下失败.Query() 引用 EmployeeModel 类中的 AllEmployees() 方法。

我尝试使用 Dapper Mapper 扩展的另一个选项,也可以在上面的代码中找到,引用 EmployeeModelMapper 类。

我的问题:

如何将所有表列映射到相应的类变量,以便在 Dapper 和扩展中通用。

最佳答案

Dapper 默认不支持 ColumnKey 等属性。

这里有两个选项,调整查询以使用 AS 关键字更改结果集中列的名称以匹配您的属性名称,这是最简单的选项。

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using Dapper;
using Newtonsoft.Json;
using Repository.DTO;

namespace Repository.Repositories
{
    public class EmployeeRepo
    {
        public IEnumerable<EmployeeModel> AllEmployees()
        {
            try
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Read"].ConnectionString))
                {
                    const string query = @"select EmpID, FirstName [First] from employee";
                    return connection.Query<EmployeeModel>(query);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(JsonConvert.SerializeObject(e));
                throw;
            }
        }
    }
}

或者,如果这不可能,您可以尝试提供自己的 SqlMapper.ITypeMap 实现。

很多人已经用许多不同的方式做到了这一点。我个人是Dapper-FluentMap的粉丝.

这将是您的 DTO。为了便于配置,我已将映射器配置嵌入到 DTO 中。请注意,您只需列出映射中与返回的列名不同的列。在我们的示例中,只需要 First 属性,因为 EmpId 属性与结果集中的列同名。

using Dapper.FluentMap.Mapping;

namespace Repository.DTO
{
    public class EmployeeModel
    {
        public int EmpId { get; set; }

        public string First { get; set; }

        public class EmployeeModelMap : EntityMap<EmployeeModel>
        {
            public EmployeeModelMap()
            {
                Map(p => p.First).ToColumn("FirstName");
            }
        }
    }
}

下一步是初始化映射。

using Dapper.FluentMap;
using Repository.DTO;

namespace Repository
{
    public class Bootstrap
    {
        public static void Map()
        {
            FluentMapper.Initialize(config =>
            {
                config.AddMap(new EmployeeModel.EmployeeModelMap());
            });
        }
    }
}

那就这样吧。

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using Dapper;
using Newtonsoft.Json;
using Repository.DTO;

namespace Repository.Repositories
{
    public class EmployeeRepo
    {
        public IEnumerable<EmployeeModel> AllEmployees()
        {
            try
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Read"].ConnectionString))
                {
                    const string query = @"select EmpID, FirstName from employee";
                    return connection.Query<EmployeeModel>(query);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(JsonConvert.SerializeObject(e));
                throw;
            }
        }
    }
}

关于c# - 如何将数据库表列映射到 Dapper .Net 中的类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21153567/

相关文章:

c# - 使用 ionic.zip 创建 zip 文件

c# - 将列指定为多个组合回归模型中的特征和标签 (ML.NET)

c# - [WCF]同一个进程中的两个服务

java - 纯面向对象语言和面向对象语言的区别

sql-server - 在一个查询中填充两个变量

c# - 当我在 if 子句中放置一个关闭的 div 标签时,Razor 会提示

c# - 注册来自不同类的回调

c# - 如何在自定义 SSIS 组件中创建目标列?

sql-server - 如何将参数传递给将执行存储过程的 SQL 作业

C# 表单通信