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

时间:2014-01-16 04:52:02

标签: 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运行Query时失败connection.Query()请参阅{{1 AllEmployees()类中的方法。

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

我的问题:

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

2 个答案:

答案 0 :(得分:2)

默认情况下,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上嵌入了mapper配置以便于配置。请注意,您只需列出映射中与返回的列名不同的列。在我们的示例中,只需要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;
            }
        }
    }
}

答案 1 :(得分:1)

一种简单的方法是将SQL select语句更改为使用AS,它将自动映射。

所以而不是:

string query = @"select e.EmpID,e.FirstName, ....

你只需要

string query = @"select e.EmpID,e.FirstName as First, ....