linq - 使用带有左连接和 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();
谁能帮我解决这个问题?
解决方案
像这样拆分您的查询,我不会使最好简单的事情复杂化
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();
推荐阅读
- autodesk-designautomation - 使用 Forge Design Automation 生成 .zip 文件
- javascript - 如何使接受数组或对象的通用 Typescript 类返回数组或对象的克隆?
- visual-studio - 在 Windows 平台上升级 Visual Studio 2019 后,Signing Identity 下拉列表为空
- javascript - 在我通过调整窗口大小强制重新渲染之前,VueJs 组件不会在模式内渲染
- sql-server - SSMS 中的“管理”在哪里?
- yocto - 不理解 packagegroup 的错误
- sql - oracle 是否支持嵌套结果集?
- python - Python 3D 中点和线段与线段上的交点之间的最短距离
- google-apis-explorer - 如何将 API Explorer 用作服务帐户?
- python - 为什么在 django 中的 Debug = False 时我在我的网站上看到服务器错误 500