Linq查询以排除相关的空实体

问题描述 投票:1回答:1

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

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

这将显示“植物”表中的所有条目以及相关植物。但是,我想从列表中排除既没有好邻居也没有坏邻居的植物。

这些是实体:植物

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;}
}

EntityBuilder

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语句来达到目的?Thnx

c# asp.net-mvc entity-framework linq
1个回答
0
投票

也许可行

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();
© www.soinside.com 2019 - 2024. All rights reserved.