Linq在group by和join之后获取子列表

4ioopgfo  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(124)

我需要将ColorModel发送到网页,以便为每个Shoe查找Stock。我想获取ColorModel的子列表,但不知道如何获取。下面是表和模型类:

public class ColorModel
{
    public int ShoeId { get; set; }
    public int ColorId { get; set; }
    public string? ColorName { get; set; } = null!;

    public List<SizeModel> Sizes { get; set; }
}

public class SizeModel
{
    public int? SizeId { get; set; }
    public float? SizeValue { get; set; }
    public int? Stock { get; set; }
}
public partial class ShoeVariant
{
    public int ShoeVariantId { get; set; }
    public int ShoeId { get; set; }
    public int ColorId { get; set; }
    public int SizeId { get; set; }
    public int Stock { get; set; }
    public virtual Color Color { get; set; } = null!;
    public virtual Shoe Shoe { get; set; } = null!;
    public virtual Size Size { get; set; } = null!;
}

public partial class Shoe
{
    public int ShoeId { get; set; }
    public string ShoeName { get; set; } = null!;
}

public partial class Size
{
    public int SizeId { get; set; }
    public float SizeValue { get; set; }
    public virtual ICollection<ShoeVariant> ShoeVariants { get; set; } = new List<ShoeVariant>();
}
var result = (
    from sv in _context.ShoeVariants
    join s in _context.Shoes on sv.ShoeId equals s.ShoeId
    join color in _context.Colors on sv.ColorId equals color.ColorId
    join sz in _context.Sizes on sv.SizeId equals sz.SizeId
    group sv by new {s.ShoeId, color.ColorId, color.ColorName} into g
    select new ColorModel
    {
        ShoeId = g.Key.ShoeId,
        ColorId = g.Key.ColorId,
        ColorName = g.Key.ColorName,
        Sizes = new List<SizeModel>
        {
        }
    }).ToList();

我应该只做单独的选择,以获得每个SizeModel列表?Stock值是在ShoeVariants

pod7payv

pod7payv1#

你应该在客户端评估分组。SQL没有类似的返回分组细节的功能。

var variants = _context.ShoeVariants
    .Select(sv => new 
    {
        ShoeId = sv.ShoeId,
        ColorId = sv.ColorId,
        ColorName = sv.Color.Name,

        Size = new SizeModel
        {
            SizeId = sv.SizeId,
            SizeValue = sv.Size.SizeValue,
            Stock = sv.Stock
        }
    })
    .AsEnumerable();

var result = variants
    .GroupBy(v => new { v.ShoeId, v.ColorId, v.ColorName })
    .Select(g => new ColorModel
    {
        ShoeId = g.Key.ShoeId,
        ColorId = g.Key.ColorId,
        ColorName = g.Key.ColorName,

        Sizes = g.Select(x => x.Size).ToList()
    })
    .ToList();

字符串

t9aqgxwy

t9aqgxwy2#

您需要在模型中定义一些导航:

public class ShoeVariant{
   
   ....
   public int ShoeId {get; set;}
   public Shoe Shoe {get; set;}
   ...

}
public class Shoe{
   
   ....
   public List<ShoeVariant> ShoeVariants {get; set;}
   ...

}

字符串
然后,你可以使用SelectMany来创建你的内部列表:

select new ColorModel
    {
        ShoeId = g.Key.ShoeId,
        ColorId = g.Key.ColorId,
        ColorName = g.Key.ColorName,
        Sizes = g.SelectMany(m=>m.Sizes)
    }


注:我更喜欢MethodStyle而不是QueryStyle,这使得它更具可读性和可维护性。

相关问题