【问题标题】:C# Linq nested class - where condition not workC# Linq 嵌套类 - 条件不起作用的地方
【发布时间】:2019-04-20 23:21:21
【问题描述】:

我有 3 个实体。我找到类别并加入 CategoryProduct,Product。 它可以工作,但“p.IsActive == true”查询不起作用。 我不想加入“p.IsActive == false” 我能做些什么?

var categoryQueryable = from c in context.Categories
                     where c.SeoUrl == seoUrl
                     join cp in context.CategoryProducts.ToList() on c.CategoryId equals cp.CategoryId
                     join p in context.Products.ToList() on cp.ProductId equals p.ProductId                                         
                     where p.IsActive == true
                     select c;


Category category = new Category();
category = categoryQueryable.FirstOrDefault<Category>();

public class Category
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CategoryId { get; set; }
    public string SeoUrl { get; set; }

    public virtual List<CategoryProduct> CategoryProducts { get; set; }
}

public class CategoryProduct
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CategoryProductId { get; set; }
    public int CategoryId { get; set; }
    public int ProductId { get; set; }

    public virtual Category Category { get; set; }
    public virtual Product Product { get; set; }
}
 public classProduct
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public bool IsActive { get; set; }

    public virtual List<CategoryProduct> CategoryProducts { get; set; }
 }

【问题讨论】:

  • 如果您只想在“产品处于活动状态”设置为 True 时加入。然后在顶部声明 var product = context.Products.Where(m=>m.IsActive==true).tolist() .. 然后在查询连接中使用这个声明的变量。
  • 当你说它不起作用时,它的字面意思是什么?这可能意味着很多事情。

标签: c# linq join nested


【解决方案1】:

谢谢你的回答。 结果现在只得到有效产品。

 var categoryQueryable = from c in context.Categories
                         where c.SeoUrl.Trim() == seoUrl.Trim()
                         join cp in context.CategoryProducts.ToList() on c.CategoryId equals cp.CategoryId
                         join p in context.Products.Where(p => p.IsActive == true).ToList() on cp.ProductId equals p.ProductId
                         select c;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 2016-11-29
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多