c# - 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 语句来实现我的目的?谢谢
解决方案
也许这可能会奏效
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();
推荐阅读
- android - Android Webview 应用程序,无法使用图像上传按钮,点击选择图像时没有任何反应
- c++ - 是 *this = Tor(); 清除对象状态是否合法有效?
- android - 如何轻松检索我的全部或部分外部 IP 地址(在 Android 设备上)?
- node.js - Req.body 为空,而我尝试了所有配置
- php - open_basedir 对父文件夹失去兴趣?
- react-native - 渐变背景不适用于屏幕
- java - 使用 Maven 和 Eclipse 创建 EAR
- qt - 如何将 QOpenGLWidget 添加到 QGraphicsScene?
- c# - C# ChatBot 在对话框之间平滑切换
- r - R 认为参数是一个函数,但实际上是一个变量