Dapper MultiMapping无法正常工作

时间:2016-05-12 15:38:47

标签: c# dapper

我尝试使用List创建Work对象Dapper来进行映射。

这是代码:

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();
}
}

它没有给我任何错误,但我返回的List中的id_modelid_type始终为空(对象已创建,但所有字段都为空或为空),其他字段正确映射。

有任何线索吗?

1 个答案:

答案 0 :(得分: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();