使用Dapper级联对象进行映射

时间:2018-10-29 15:29:15

标签: c# dapper

我正在重构用EF进行的旧查询,该查询要花费大量时间。 我想知道是否可以自动映射此类对象

public class Chest
{
  public Item Item {get;set;}
}

public class Item
{
   public IList<Property> Properties {get;set;}
}

public class Property
{
    public int Id {get;set;}
    public string Description {get;set;}
}

是否可以像使用EF一样检索所有这些项目?

我看过查询等等,但我不知道它是否符合要求

1 个答案:

答案 0 :(得分:1)

您的模型非常简单,因为只有1个集合-IList<Property>,假设您的查询是Select Id, Description from PropertyTable,然后使用Dapper,您可以执行以下操作:

IList<Property> PropertyList = conn.Query<Property>("Select Id, Description from PropertyTable").ToList();

简单分配之后:

Chest chest = new Chest{Item = new Item{Properties = PropertyList}};

这仍然需要额外的分配,因为从Dapper获得的IEnumerable<T>可能是Dapper Extension,如果您提供显式的对象映射,则可以直接填充Chest对象,尽管我认为它不是必需的,因为解决方案很简单