【问题标题】:Fetch data using LINQ query with left join and AsExpandable()使用带有左连接和 AsExpandable() 的 LINQ 查询获取数据
【发布时间】:2019-04-05 10:37:13
【问题描述】:

我有以下两个表格:图片和文章

两个表都由 ImageId 列链接。

一张图片可以关联多篇文章。

例如:Images 表有 100 行,Articles 表有 200 行。

在这 100 张图片中,假设文章中仅使用了 90 张。在这种情况下,一些图片在许多文章中重复出现。

在这里,我想获取未使用的 10 张图片(来自 Images 表),并且还想包含与文章关联不超过 2 次的图片。我想忽略那些与文章关联超过 2 次的图片。

我尝试了以下 linq 查询,但它不适合我。

 var predicate = PredicateBuilder.True<Image>();
                if (type != null && type != 0)
                {
                    predicate = predicate.And(c => c.ImageType == type);
                }
                if (!string.IsNullOrWhiteSpace(keyword))
                {
                    predicate = predicate.And(c => c.Name.Contains(keyword) || c.Keyword.Contains(keyword));
                }

                int skip = numberofImages * (page - 1);

var images = (from imgs in context.Images
                              join art in context.Articles on imgs.ImageId equals art.ImageId into unusedImages
                              from img in unusedImages.DefaultIfEmpty()
                              group img by imgs.ImageId into grouped                              
                                   .AsExpandable()
                                   .Where(predicate)
                              orderby Guid.NewGuid(), imgs.ImageId descending
                              select imgs)
                                   .Skip(skip).Take(numberofImages).ToList();

谁能帮我解决这个问题?

【问题讨论】:

  • 您的代码看起来应该失败 - .AsExpandable() 属于什么?该代码肯定不会编译。 predicate的定义是什么?
  • 我现在已经更新了代码。 AsExpandable() 是 LinqKit 的一部分 (albahari.com/nutshell/predicatebuilder.aspx)
  • 我知道是什么——grouped之后就不能用了。
  • orderby imgsgroup 之后也不能这样做
  • 非常感谢任何其他解决方法或替代解决方案来解决此问题

标签: linq c#-4.0


【解决方案1】:

像这样拆分你的查询,我不会把最好是简单的事情复杂化

var usedArticles = (from item in  context.Articles
                    group item by imageid into newList
                    select new 
                      { 
                       imageid = newList.key,
                       count =newlist.count
                       }).ToList();  
var unwaantedImageIds = usedArticles.where(x=>x.count>2).Select(y=>y.imageId).ToArray();

   var unwantedImages =context.image.where(x=>unwaantedImageIds.contains(x.imageId));
    var result =  context.images.Except(unwaantedImageIds).ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多