c# - linq 的内部左连接返回太多结果

标签 c# linq linq-to-sql repository-pattern

自从我上次使用内部连接以来已经很多年了,所以我有点生疏了。 它有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/

相关文章:

c# - 从 Linq 查询中选择多列

c# - NHibernate IQueryable.SingleOrDefault 在子查询中。使用函数谓词而不执行

c# - 算法挑战 : merging date range

c# - 使用 LINQ 查询单个列

c# - 使用 LINQ to SQL 时避免连接超时的最佳实践

c# - Internet Explorer 9 身份验证问题——URL 中的奇怪字符

C# - Windows Phone - MaxWidth 和 MaxHeight 属性被忽略

c# - 如果用户开始使用 @ 特殊字符(如 whatsapp 标记功能)打字,Xamarin Android 如何显示列表?

c# - 如何在运行时向 ItemTemplate (Repeater) 添加控件?

c# - 自定义属性和 lambda 表达式