【问题标题】:Inner left join with linq returns too many results带有 linq 的内左连接返回太多结果
【发布时间】:2013-03-16 19:53:33
【问题描述】:

自从我上次使用内部连接以来,我已经有好几年了,所以我有点生疏了。 它有 3 张桌子

相册、相册图片和用户

现在首先在我的存储库中,i Inner Left Join Album 和 AlbumsImages,问题是我只想要从 Albumsimages 中的第一个输入,按先 Cover Desc 然后 Id Desc 排序(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,
                });

【问题讨论】:

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


    【解决方案1】:

    albumImages 中删除DefaultIfEmpty。无论是否匹配(左连接),这都会返回专辑图像。

    【讨论】:

    • 是的,我忘了补充说一个相册可以有 0 张图片,我仍然希望在那个实例中输出相册
    • @DoomStone 然后将您的第二个查询更改为使用DefaultIfEmpty 执行into
    • 我不明白,你想让用户表加入一个 into 和 DefaultIfEmpty 吗?总会有一个具有给定用户 ID 的用户!
    • @DoomStone 抱歉,您必须重写第一个查询以执行from i in _imageRepository.Get(),然后在专辑表上执行连接DefaultIfEmpty,这样您将始终获得所有专辑。
    • 我已经尝试按照您所说的去做:D 请参阅我的 OP 中的“测试”,但它返回的结果与其他方法相同 :( @mattytommo
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 2018-01-10
    相关资源
    最近更新 更多