自上次使用内部联接以来已经有好几年了,所以我有点生锈。
它有3张桌子
专辑,专辑图片和用户
现在首先在我的存储库i左内连接相册和AlbumsImages中,问题是我只希望按firs Cover Desc依次从IDs Desc到Albumsimages顺序的第一个Enter(在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,
});
最佳答案
从DefaultIfEmpty
起飞albumImages
。无论是否存在匹配项,这都将返回专辑图像(左联接)。