在EF Core 3.1.1中联接3个表并将左外部联接与linq一起使用

问题描述

我有3个表,NoticesUsersLikes。如果用户喜欢此通知,我想获得所有带有用户名和信息的通知

到目前为止,我已经有了这段代码,但是它多次返回一个通知(每个类似一次):

return context.notices
        .GroupJoin(context.Users,notice => notice.CreatedBy,user => user.Id,(notice,users) => new { notice,users })
        .SelectMany(group => group.users.DefaultIfEmpty(),(group,user) =>
        new
        {
            group.notice,user
        })
        .GroupJoin(context.Likes,noticeDto => noticeDto.notice.Id,like => like.ItemId,(noticeDto,likes) => new { noticeDto,likes })
        .SelectMany(group => group.likes.DefaultIfEmpty(),like) =>
        new NoticeDto
        {
            CreatedByName = (group.noticeDto.user == null ? "" : group.noticeDto.user.FullName),Id = group.noticeDto.notice.Id,Liked = like.CreatedBy == userId,});

我也尝试了这段代码..但是我收到一个错误

return context.notices
                .GroupJoin(context.Users,users })
                .SelectMany(group => group.users.DefaultIfEmpty(),user) =>
                new
                {
                    group.notice,user
                })
                .GroupJoin(context.Likes,likes })
                .Select((group) =>
                new NoticeDto
                {
                    CreatedByName = (group.noticeDto.user == null ? "" : group.noticeDto.user.FullName),Liked = group.likes != null ? group.likes.Any(w => w.CreatedBy == userId) : false,});

这是我得到的错误

LINQ表达式'DbSet的处理 .LeftJoin( 外部:DbSet .AsQueryable(), 内部:注意=>注意.CreatedBy, externalKeySelector:用户=> user.Id, innerKeySelector :(通知用户)=>新{ 通知=通知用户=用户 }) .GroupJoin( 外部:DbSet, 内部:noticeDto => noticeDto.notice.Id, externalKeySelector:喜欢=> like.ItemId, innerKeySelector:(noticeDto,点赞)=>新{ noticeDto =注意Dto, 喜欢=喜欢 })'
通过“ NavigationExpandingExpressionVisitor”失败。这可能表示EF Core中存在错误或限制。

任何人都可以帮助我实现我所需要的吗?。谢谢。

通知

    public Guid Id { get; set; }
    public Guid CreatedBy { get; set; }

用户

 public Guid Id { get; set; }
 public string FullName{ get; set; }

    public Guid Id { get; set; }
    public Guid CreatedBy { get; set; }
    public Guid ItemId { get; set; }

解决方法

喜欢的ItemId是公告的ID?通知和Like的CreatedBy是用户的ID?

如果是这样,请尝试这个。

return context.notices.Include(x => x.Users)
                      .Include(x => x.Likes)
                      .Include("Likes.Users");

数据库

enter image description here

结果

enter image description here

已编辑

由于您没有外键和关系,因此可以尝试

var users = context.Users;
        
return context.notices.Select(x => new Notice() 
{
     Id = x.Id,CreatedBy = x.CreatedBy,Users = users.Where(y => y.Id == x.CreatedBy).FirstOrDefault(),Likes = context.Likes.Where(y => y.ItemId == x.Id)
                    .Select(y => new Likes()
                    {
                        Id = y.Id,CreatedBy = y.CreatedBy,ItemId = y.ItemId,Users = users.Where(z => z.Id == y.CreatedBy).FirstOrDefault()
                    }).ToList()
});