使用具有左联接和AsExpandable()的LINQ查询获取数据

时间:2019-04-05 10:37:13

标签: linq c#-4.0

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

两个表都由ImageId列链接。

一个图像可以与多个文章相关联。

例如:“图像”表有100行,“文章”表有200行。

在这100张图像中,假设只有90条用于所有文章。在这种情况下,某些图片会在许多文章中重复出现。

在这里,我想获取未使用的10张图像(从“图像”表中),并且还希望包含与文章关联的图像不超过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();

enter image description here

任何人都可以帮助我解决此问题吗?

1 个答案:

答案 0 :(得分: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();