【发布时间】:2020-09-26 10:43:18
【问题描述】:
在我当前的项目中,我想显示与 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 语句来实现我的目的? 谢谢
【问题讨论】:
-
你能发布植物模型和依赖模型吗?
-
查看我上面编辑过的帖子
-
这篇文章可能会回答您的问题how-to-load-the-navigation-property-with-ef-core
-
我收到错误消息,即 lambda 表达式不是
Include语句中的有效表达式。我试过了:.Include(p => p.BadNeighbours.Where(bn => bn.PlantId == p.Id || bn.BadNeighbourId == p.Id)) -
您应该显示整个查询,而不仅仅是
Where。也许你有一个Select让 EF 忽略Includes。
标签: c# asp.net-mvc entity-framework linq