提问者:小点点

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


在我当前的项目中,我想要显示一个条目列表,这些条目具有与它们相关的ICollections。 植物与坏邻居和好邻居都有多对多的关系。 我使用的Linq语句是:

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

这将显示Plants表中包含相关植物的所有条目。 然而,我想把那些既没有好邻居也没有坏邻居的植物排除在名单之外。

这些是实体:植物

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

我尝试在最后一个include语句之后添加where(p=>p.GoodNeighbours.count()>0&&p.BadNeighbours.count()>0,虽然这在我的ICollection plants中得到了正确的植物数量,但是GoodNeighbours和BadNeighbours关系不再包含。

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


共1个答案

匿名用户

这是另一种选择。

我认为工厂有许多坏邻居好邻居

试试看

ICollection<Plant> plants = _context.Plants
   .Where(p => _context.BadNeighbours.Any(nb => nb.PlantId != p.Id))
   .Where(p => _context.GoodNeighbours.Any(nb => nb.PlantId != p.Id))
   .ToList();

ICollection<Plant> plants = _context.Plants
   .Where(p => !_context.BadNeighbours.Any(nb => nb.PlantId == p.Id))
   .Where(p => !_context.GoodNeighbours.Any(nb => nb.PlantId == p.Id))
   .ToList();

另外,上面的内容可以编译成带有exist子句的查询