首页 > 解决方案 > Linq 查询排除相关实体为空

问题描述

在我当前的项目中,我想显示与 ICollections 相关的条目列表。Plant 与 BadNeighbours 和 GoodNeighbours 都具有多对多关系。我使用的 Linq 语句是:

ICollection<Plant> plants = _context.Plants
                .Include(p => p.BadNeighbours)
                .Include(p => p.GoodNeighbours)
                .ToList();

这将显示植物表中的所有条目以及相关植物。但是,我想从列表中排除既没有 GoodNeighbours 也没有 BadNeighbours 的植物。

这些是实体: 植物

public class Plant
{

    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<GoodPlants> GoodNeighbours { get; set; }
    public virtual ICollection<BadPlants> BadNeighbours { get; set; }
}

坏邻居

public class BadPlants
{
    public int PlantId { get; set; }
    public int BadNeighbourId { get; set; }

    public virtual Plant Plant { get; set; }
    public virtual Plant BadNeighbour { get; set; }
}

好邻居

public class GoodPlants
{
    public int PlantId { get; set; }
    public int GoodNeighbourId { get; set; }

    public virtual Plant Plant { get; set; }
    public virtual Plant GoodNeighbour {get; set;}
}

实体生成器

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);
   modelBuilder.Entity<Plant>().HasKey(p => p.Id);
   modelBuilder.Entity<BadPlants>()
    .HasKey(u => new { u.BadNeighbourId, u.PlantId });

   modelBuilder.Entity<GoodPlants>()
    .HasKey(u => new { u.GoodNeighbourId, u.PlantId });

   modelBuilder.Entity<Plant>()
    .HasMany(p => p.GoodNeighbours)
    .WithOne(g => g.Plant)
    .HasForeignKey(g => g.PlantId)
    .OnDelete(DeleteBehavior.NoAction);

   modelBuilder.Entity<Plant>()
   .HasMany(p => p.BadNeighbours)
   .WithOne(b => b.Plant)
   .HasForeignKey(b => b.PlantId)
   .OnDelete(DeleteBehavior.NoAction);            
}

我试图Where(p => p.GoodNeighbours.Count() > 0 && p.BadNeighbours.Count() > 0)在最后一条include语句之后添加,虽然这导致我的植物数量正确ICollection plants,但关系 GoodNeighbours 和 BadNeighbours 不再包括在内。

我可以使用什么 Linq 语句来实现我的目的?谢谢

标签: c#asp.net-mvcentity-frameworklinq

解决方案


也许这可能会奏效

ICollection<Plant> plants = _context.Plants
   .Where(p => !_context.BadPlants.Any(nb => nb.PlantId == p.Id || nb.BadNeighbourId == p.Id))
   .Where(p => !_context.GoodPlants.Any(nb => nb.PlantId == p.Id || nb.GoodNeighbourId == p.Id))
   .ToList();

推荐阅读