2016-05-12 62 views
0

我在嘗試使用Dapper來創建對象WorkList以進行映射。Dapper MultiMapping不起作用

這是代碼:

public class Work 
{ 
    public int id { get; set; } 
    public int id_section { get; set; } 
    public decimal price { get; set; } 
    public Model id_model { get; set; } 
    public Type id_type { get; set; } 
} 

class Model 
{ 
    public int id_model { get; set; } 
    public string Name { get; set; } 
} 

class Type 
{ 
    public int id_type { get; set; } 
    public string Name { get; set; } 
} 

public List<Work> GetListOfWork(int idList) 
{ 
using (DatabaseConnection db = new DatabaseConnection()) //return a connection to MySQL 
{ 
    var par = new {Id = idList}; 
    const string query = "SELECT id,id_section,price,id_model,id_type FROM table WHERE id_section = @Id"; 
    return db.con.Query<Work, Model, Type, Work>(query, 
      (w, m, t) => 
      { 
       w.id_model = m; 
       w.id_type = t; 
       return w; 
      }, par, splitOn: "id_model,id_type").ToList(); 
} 
} 

它不給我任何錯誤,但id_modelid_type在我返回列表總是空的(對象被創建,但所有的字段爲空或空) ,其他字段映射正確。

任何線索?

+0

而且怎麼可能填補任何東西,如果你不從數據庫中檢索的字段,缺少一些加入? – Steve

+0

由於我的查詢很複雜(這只是一個例子),手動執行映射會不好嗎?就像創建一個使用Model和Type的構造函數映射ListOfWork的函數一樣? – SilentRage47

回答

1

您需要添加自己的查詢字符串 的加入也許這是這樣的

var par = new {Id = idList}; 
const string query = @"SELECT w.id,w.id_section,w.price, 
         m.id_model, m.Name, t.id_type, t.Name 
         FROM work w INNER JOIN model m on w.id_model = m.id_model 
            INNER JOIN type t on w.id_type = t.id_type 
         WHERE w.id_section = @Id"; 
return db.con.Query<Work, Model, Type, Work>(query, 
     (w, m, t) => 
     { 
      w.id_model = m; 
      w.id_type = t; 
      return w; 
     }, par, splitOn: "id_model,id_type").ToList();