首页 > 解决方案 > 使用带有左连接和 AsExpandable() 的 LINQ 查询获取数据

问题描述

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

这两个表都由 ImageId 列链接。

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

例如:图像表有 100 行,文章表有 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();

在此处输入图像描述

谁能帮我解决这个问题?

标签: linqc#-4.0

解决方案


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

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

推荐阅读