如何在 ICollection LINQ 结果上应用 where 子句?

问题描述 投票:0回答:1

我的项目中有三个课程:

public partial class Product
{
 public string? Title { get; set; }
 public string? UrlAddress { get; set; }
 public virtual ICollection<ProductSize> ProductSizes { get; set; }
 public virtual Picture? Picture { get; set; }
 
}


public partial class ProductSize
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public int SizeId { get; set; }

    public virtual Product Product { get; set; } = null!;
    public virtual Size Size { get; set; } = null!;
}


public partial class Size
{
  public int Id { get; set; }
  public int? ProductTypeId { get; set; }
  public string Name { get; set; } = null!;
}

并尝试使用此 linq 查询获得一些结果:

var result =   _tebpooshContext.Products
   .Where(p => p.ProductCategoryId == 1
            && p.ProductTypeId == 2
   )
   
   .Include(p => p.Picture)
   .Include(p => p.ProductSizes)
   .ThenInclude(p => p.Size)
   
   .Select(p => new TileProductDto
   {
       Image = p.Picture.Url.Replace("SYSTEM_TYPE_SYNCSERVER", "URL"),
       Name = p.Name.Trim(),
       Price = p.Price.ToString(),
       ProductSizes = p.ProductSizes,
       ProdutId = p.Id.ToString(),


   })

   .Take(9).ToList();

现在尝试使用以下语法在

Take(9)
之前编写此 where 子句:

.Where(p => p.ProductSizes.Where(p => p.Size.Name == "42"))

但出现此错误:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<TebWebApp.models.entities.ProductSize>' to 'bool'    

尝试用这种方式修复该错误:

.Where(p => p.ProductSizes.Any(p => p.Size.Name == "42"))

但是 where 子句返回所有产品尺寸和尺寸“42”不会影响 where 子句。

如何在

Take(9)
之前应用我的 where 子句?

c# linq entity-framework-core
1个回答
0
投票

首先,当查询以投影结束时(即

Include
语句),
Select(x => new ...)
会被忽略。它们应该被删除(代码不应包含冗余)。

你想要的可以通过在投影中添加

Where
来实现:

var result = _tebpooshContext.Products
   .Where(p => p.ProductCategoryId == 1
            && p.ProductTypeId == 2)
   .Select(p => new TileProductDto
   {
       Image = p.Picture.Url.Replace("SYSTEM_TYPE_SYNCSERVER", "URL"),
       Name = p.Name.Trim(),
       Price = p.Price.ToString(),
       ProductSizes = p.ProductSizes.Where(p => p.Size.Name == "42"), // here
       ProdutId = p.Id.ToString(),
   })
   .Take(9).ToList();
© www.soinside.com 2019 - 2024. All rights reserved.