Dapper ORM 3层MultiMapping

时间:2019-06-17 09:46:33

标签: c# asp.net-mvc dapper

我正在使用Dapper,我有这些课程

public class Shape
{
    public Shape()
    {
        ShapeDetails = new List<ShapeDetail>();
    }

    public int ID { get; set; }
    public string Name { get; set; }
    [NonPersistent]
    public List<ShapeDetail> ShapeDetails { get; set; }
}

public class ShapeDetail
{
    public int ID { get; set; }
    public decimal RangeFrom { get; set; }
    public decimal RangeTo { get; set; }
    public decimal Price { get; set; }
    public int ShapeID { get; set; }
    [NonPersistent]
    public Shape Shape { get; set; }
}

根据我在Dapper网站上看到的教程,这就是我的做法

var shapeDictionary = new Dictionary<int, Shape>();

return connection.Query<Shape, ShapeDetail, Shape>(
    "SELECT * FROM Shape INNER JOIN ShapeDetail ON Shape.ID = 
        ShapeDetail.ShapeID",
                    (shape, shapeDetail) =>
                    {
                        Shape shapeEntry;

                        if (!shapeDictionary.TryGetValue(shape.ID, out shapeEntry))
                        {
                            shapeEntry = shape;
                            shapeEntry.ShapeDetails = new List<ShapeDetail>();
                            shapeDictionary.Add(shapeEntry.ID, shapeEntry);
                        }

                        shapeEntry.ShapeDetails.Add(shapeDetail);
                        return shapeEntry;
                    },
                    splitOn: "ID")
                .Distinct()
                .ToList();

但是,如果我有3层集合,该如何在单个查询中映射所有这些类?

public class ItemType
{
    public ItemType()
    {
        SubItems = new List<SubItem>();
    }

    public int ID { get; set; }
    public string Name { get; set; }
    public bool Hidden { get; set; }
    [NonPersistent]
    public List<SubItem> SubItems { get; set; }
}

public class SubItem
{
    public SubItem()
    {
        WorkLevels = new List<WorkLevel>();
    }

    public int ID { get; set; }
    public string Name { get; set; }
    public bool ShowGender { get; set; }
    public int ItemTypeID { get; set; }
    [NonPersistent]
    public List<WorkLevel> WorkLevels { get; set; }
    [NonPersistent]
    public ItemType ItemType { get; set; }
}

public class WorkLevel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int SubItemID { get; set; }
    [NonPersistent]
    public SubItem SubItem { get; set; }
}

任何回应将不胜感激

0 个答案:

没有答案