自从我上次使用内部连接以来已经很多年了,所以我有点生疏了。 它有3张 table
相册、相册图像和用户
现在首先在我的存储库中,在左侧加入相册和相册图像,问题是我只想要相册图像中的第一个条目,先按封面描述,然后是 Id 描述(AlbumImages 中可以有 0 个图像!)。之后,我加入我的用户表,将相册中的用户 ID 添加到用户中的 ID。 我的问题是我不只得到 1 个相册,而是 albumsImages 中每个图像的结果,其中我只想要 1 个。 我在这里做错了什么?
public IQueryable<Album> Get()
{
return (from a in context.Albums
join i in _imageRepository.Get() on a.Id equals i.AlbumId into albumImages
from cover in albumImages.DefaultIfEmpty()
orderby cover.Cover descending, cover.Id ascending
select new Album()
{
Id = a.Id,
UserId = a.UserId,
Name = a.Name,
Created = a.Created,
LastEdit = a.LastEdit,
Description = a.Description,
Views = a.Views,
Location = a.Location,
Photoshoot = a.Photoshoot,
Cover = cover,
});
}
var albums = (from a in AlbumRepository.Get()
join u in UserRepository.Get() on a.UserId equals u.Id
orderby a.Id descending
select new AlbumDisplayModel()
{
Album = a,
User = u
}).ToList();
测试:
return (from i in _imageRepository.Get()
join album in context.Albums on i.AlbumId equals album.Id into albums
from a in albums.DefaultIfEmpty()
select new Album()
{
Id = a.Id,
UserId = a.UserId,
Name = a.Name,
Created = a.Created,
LastEdit = a.LastEdit,
Description = a.Description,
Views = a.Views,
Location = a.Location,
Photoshoot = a.Photoshoot,
Cover = i,
});
最佳答案
从 albumImages
中删除 DefaultIfEmpty
。无论是否匹配(左连接),都会返回专辑图像。
关于c# - linq 的内部左连接返回太多结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15646903/