从单个(平面)数据库查询

时间:2017-07-20 23:18:04

标签: c# linq

我通过SQL查询从ERP获取产品数据,其中返回的数据非常平坦 - 在大小级别。产品有3个级别:

  • 风格
  • 颜色
  • 尺寸

样式有很多种颜色,颜色有很多种。

我创建了以下模型:

public class Ap21Style
{
    public int StyleIdx;
    public string StyleCode;
    public IList<Ap21Clr> Clrs { get; set; } = new List<Ap21Clr>();
}

public class Ap21Clr
{
    public int ClrIdx { get; set; }
    public string ColourCode { get; set; }
    public string ColourName { get; set; }
    public string ColourTypeCode { get; set; }
    public string ColourTypeName { get; set; }
    public IList<Ap21Sku> Skus { get; set; } = new List<Ap21Sku>();
}

public class Ap21Sku
{
    public int SkuIdx { get; set; }
    public string SizeCode { get; set; }
    public int SizeSequence { get; set; }
    public string Barcode { get; set; }
}

我的ProductResult看起来像这样:

public int StyleIdx { get; set; }
public int ClrIdx { get; set; }
public int SkuIdx { get; set; }
public string StyleCode { get; set; }
public string ColourCode { get; set; }
public string ColourName { get; set; }
public string SizeCode { get; set; }
public int SizeSequence { get; set; }
public string ColourTypeCode { get; set; }
public string ColourTypeName { get; set; }
public string Barcode { get; set; }
public string WebData { get; set; }

循环结果并创建Ap21Style模型的有效方法是什么,它们是Ap21Clr&#39; s的复合对象,然后在行级别,颜色有Ap21Sku&#39;?的

1 个答案:

答案 0 :(得分:8)

假设这样的事情

List<ProductResult> products = GetPropducts();

组合样式将涉及通过组合键对数据进行分组

List<Ap21Style> results = products
    .GroupBy(p => new { p.StyleIdx, p.StyleCode })
    .Select(g => new Ap21Style {
        StyleIdx = g.Key.StyleIdx,
        StyleCode = g.Key.StyleCode,
        Clrs = g.GroupBy(s => new {
            s.ClrIdx,
            s.ColourCode,
            s.ColourName,
            s.ColourTypeCode,
            s.ColourTypeName
        }).Select(g1 => new Ap21Clr {
            ClrIdx = g1.Key.ClrIdx,
            ColourCode = g1.Key.ColourCode,
            ColourName = g1.Key.ColourName,
            ColourTypeCode = g1.Key.ColourTypeCode,
            ColourTypeName = g1.Key.ColourTypeName,
            Skus = g1.Select(s => new Ap21Sku {
                Barcode = s.Barcode,
                SizeCode = s.SizeCode,
                SizeSequence = s.SizeSequence,
                SkuIdx = s.SkuIdx
            }).ToList()
        }).ToList()
    }).ToList();