2014-01-16 81 views
2

我有一個名爲employee的表,它有幾個列,如EmpID,FirstName,MiddleName,LastName,Address,EmailID,RegionID,DesgID,我使用Dapper .Net和擴展來處理SQL Server數據庫。我使用Dapper SqlExtensions來插入,更新,刪除功能,並使用Dapper multimapper選項來填充細節。所以就用下面類以上employee如何將數據庫表列映射到Dapper .Net中的類屬性

[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但它在使用小巧玲瓏運行查詢的情況下失敗connection.Query()指的AllEmployees()方法在EmployeeModel類中。

另外一個選項,我嘗試使用Dapper Mapper擴展,也可以在上面的代碼中找到,請參閱EmployeeModelMapper類。

我的問題:

如何將所有表列映射到對應的類變量,以在小巧玲瓏和擴展共同使用。

回答

1

一個簡單的方法是將您的SQL select語句更改爲使用AS,它將自動映射。

所以不是:

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

你只需要

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

我知道。但我想通過映射類屬性來克服這一點。這是我的要求...... :(和thnx您的suggession ... :) –

2

小巧玲瓏的默認情況下不支持財產屬性,如ColumnKey

這裏有兩個選項,ether調整查詢以使用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; 
      } 
     } 
    } 
} 
相關問題