Entity Framework核心:获取相关数据

Entity Framework Core: get related data

在我正在开发的应用程序中,我的用户可以拥有播放列表。他们可以访问自己的播放列表(他们随后将成为该播放列表的所有者)或与他们所属团队相关的播放列表。我的实体如下所示(Id 是 Guid 类型,并且继承自实体 AuditEntity):

public class Team : AuditEntity
{
    public Team()
    {
        Playlists = new HashSet<Playlist>();
    }

    public string TeamName { get; set;}

    public Guid OwnerId { get; set; }
    public virtual AppUser Owner { get; set; }

    public ICollection<TeamsAppUsers> Members { get; set; }
    public ICollection<Playlist> Playlists { get; private set; }
}

public class Playlist : AuditEntity
{
    public string PlaylistName { get; set; }    

    public Guid OwnerId { get; set; }
    public virtual AppUser Owner { get; set; }

    public Team Team { get; set; }
}

public class TeamsAppUsers
{
    public Guid AppUserId { get; set; }
    public AppUser Member { get; set; }

    public Guid TeamId { get; set; }
    public Team Team { get; set; }
}

我需要所有播放列表(并且只需要一次),其中用户要么是所有者,要么是与播放列表相关的团队的成员。

对于 OwnerId 我有:

var playlists = await _context.Playlists
                              .Where(pl => pl.OwnerId == userId)
                              .ToListAsync()

我如何扩展此声明,以便它也包括用户是相关团队成员的播放列表?

您可以将代码移动到您的上下文中并使用 EntityFramework,我允许自己在几个地方编辑您的类型以便能够建立模型构建关系,如下所示:


    public class PlaylistsDbContext : DbContext
    {
        DbSet Teams { get; set; }
        DbSet Playlists { get; set; }
        DbSet AppUsers { get; set; }
        //Not needed
        DbSet TeamAppUsers { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity().HasKey(k => k.Id);
            modelBuilder.Entity().HasKey(k => k.Id);
            modelBuilder.Entity().HasKey(k => k.AppUserId);
          
            //Not needed
            modelBuilder.Entity().HasKey(k => new { k.AppUserId, k.TeamId });

            modelBuilder.Entity().HasMany(x => x.Playlists).WithOne(y => y.Team);
            modelBuilder.Entity()
                .HasOne(x => x.Owner)
                .WithMany(y => y.PlayLists)
                .HasPrincipalKey(k => k.AppUserId)
                .HasForeignKey(f => f.OwnerId);
            modelBuilder.Entity()
                .HasOne(x => x.Team)
                .WithMany(y => y.Playlists)
                .HasPrincipalKey(p => p.Id)
                .HasForeignKey(f => f.TeamId);

            //These relationship tables can be omitted, as entity framework can handle that for You
            //Then you can also drop the explicit foreign key fields
            
            base.OnModelCreating(modelBuilder);
        }

        public List GetUserPlaylists(Guid userId)
        {
            return Playlists.Include(x => x.Owner).Include(y => y.Team)
                .Where(z => z.Owner.AppUserId == userId
                                || z.Team.Members.Any(m => m.AppUserId == userId))
                .Distinct()
                .ToList();
        }
    }