带有两个集合的where子句中的LINQ表达式

时间:2014-09-25 13:21:22

标签: c# sql linq entity-framework

我必须在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());

抛出的异常是:&#34;在此上下文中仅支持基本类型或枚举类型。&#34;

编辑:标题是ICollection

1 个答案:

答案 0 :(得分:1)

两件事:

  1. 在您正在尝试比较对象的WHERE子句中,当LINQ将您的查询转换为SQL时,它无法转换这些对象。您必须选择ID并对其进行比较,或使用导航属性。
  2. 您仍在手动循环收集,这不是LINQ的意思。选择您需要的,然后在下一步中使用它。
  3. 应该有用的东西:

    // 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();