【问题标题】:LINQ expression in where clause with two collections带有两个集合的 where 子句中的 LINQ 表达式
【发布时间】:2014-09-25 13:21:22
【问题描述】:

我必须在 where 子句中有两个 ICollections 进行查询,但我尝试过的没有任何工作在这里是我尝试过的:

    var segmentActivity = db.Activities.Where(x => x.Segment.Link == link).ToList();

    ICollection<Heading> hd = new List<Heading>();
    foreach(var activity in segmentActivity)
    {
        hd.Add(db.Headings.Where(x => x.ActivityId == activity.Id).First());
    }            

    ICollection<ProdutoSegmentoVM> produtos = new List<ProdutoSegmentoVM>();
    foreach(var produto in hd)
    {
                    //this is the where clause that i'm having problem v
        produtos.Add(db.Products.Where(x => hd.Contains(x.Headings.Where(h => h.Id == produto.Id).First())).Select(x => new ProdutoSegmentoVM()
        {
            Id = x.Id,
            Description = x.Description,
            IsSpecification = (x.Specifications != null) ? true : false,
            Specification = (x.Specifications != null) ? x.Specifications.Select(s => new SpecItemVM() 
                            { 
                                Attribute = s.Attribute, 
                                Detail = s.SpecificationValues.Select(v => v.Detail).ToList()
                            })
                            .ToList() : null,
            Image = x.PrimaryImage.Name,
            SubTitle = x.Subtitle,
            Title = x.TitleMetadata
        })
        .First());

抛出的异常是:“此上下文仅支持原始类型或枚举类型。”

编辑:标题是一个ICollection

【问题讨论】:

    标签: c# sql linq entity-framework


    【解决方案1】:

    两件事:

    1. 在 WHERE 子句中,您尝试比较对象,当 LINQ 将您的查询转换为 SQL 时,它无法转换这些对象。您必须选择 id 并进行比较,或者使用导航属性。
    2. 您仍在手动循环遍历集合,这不是 LINQ 的意义所在。选择您需要的内容,然后在下一步中使用它。

    类似的东西应该可以工作:

    // Select activity-id's
    var activityIds = db.Activities
        .Where(x => x.Segment.Link == link)
        .Select(x => x.Id);
    
    // Use activity-id's to select heading-id's
    var headingIds = db.Headings
        .Where(x => activityIds.Contains(x.ActivityId))
        .Select(x => x.Id);
    
    var produtos = db.Products
        .Where(x => headingIds.Contains(x.Id))
        .Select(x => new {
            ...
        })
        .ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多