[英]Linq query to exclude related entities that are empty
在我當前的項目中,我想顯示與 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);
}
我嘗試在最后一個include
語句之后添加Where(p => p.GoodNeighbours.Count() > 0 && p.BadNeighbours.Count() > 0)
,盡管這會導致我的ICollection plants
中的植物數量正確,但關系 GoodNeighbours 和 BadNeighbours 不再包括在內。
我可以將什么 Linq 語句用於我的目的? 謝謝
也許這可能會奏效
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.