如何在一个实体B的集合中查询包含任何实体B的所有实体A?[英] How to query for all EntityA that contain any EntityB within a collection of EntityBs?

本文是小编为大家收集整理的关于如何在一个实体B的集合中查询包含任何实体B的所有实体A?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

本文来自:IT宝库(https://www.itbaoku.cn)

给定以下两个示例C#实体类...

class EntityA
{
  public int EntityAId { get; set; }
  public virtaul ICollection<EntityB> Bs { get; set; }
}

class EntityB
{
  public int EntityBId { get; set; }
  public string Foobar { get; set; }
  public virtual EntityA A { get; set; }
}

我将如何使用实体框架 + linq查询所有EntityA在提供的EntityB>>>?

中包含任何EntityB的所有EntityA

澄清,如果我有以下EntityB ...

的子集
var bs = new List<EntityB>
{
  new EntityB { Foobar = "a" },
  new EntityB { Foobar = "b" },
  new EntityB { Foobar = "c" }
};

我想找到全部EntityA其中EntityA.Bs集合包含上述bs集合中的任何可能的EntityB.

推荐答案

因此,当您最初问时,我以为您的意思是您只有一个eNtityB的dbset.现在,我看到您正在尝试使用给定集中定义的EntityB找到任何Entitya,我们可以简化这一点:

var bs = your collection of EntityB
var dbSet = dbSet of type EntityA
var entities = dbSet.Where(m => m.Bs.Any(b =>
    bs.Any(b2 => b2.Foobar == b.Foobar).ToList();

因此,这将浏览一个Entitya的集合,并将返回具有任何具有foobar的EntityB等于给定集合中任何的Entitya.

我会从Entitya查询,因为您收到了一个Entityas的集合.但是,如果您想从EntityB那里进行以下操作.

var entities = entityBSet.Where(m => 
    bs.Any(b => 
        b.Foobar == m.Foobar))
    .Select(m => m.A)
    .ToList();

本文地址:https://www.itbaoku.cn/post/1557226.html

问题描述

Given the following two example C# entity classes ...

class EntityA
{
  public int EntityAId { get; set; }
  public virtaul ICollection<EntityB> Bs { get; set; }
}

class EntityB
{
  public int EntityBId { get; set; }
  public string Foobar { get; set; }
  public virtual EntityA A { get; set; }
}

How would I go about using Entity Framework + LINQ to query for all EntityA that contain any EntityB within a provided collection of EntityB?

To clarify, if I have the following subset of EntityB ...

var bs = new List<EntityB>
{
  new EntityB { Foobar = "a" },
  new EntityB { Foobar = "b" },
  new EntityB { Foobar = "c" }
};

I want to find all EntityA where EntityA.Bs collection contains any of the possible EntityB within the above bs collection.

推荐答案

So when you originally asked I thought you meant you only had a dbSet of EntityB. Now that I see you're trying to find any EntityA with an EntityB defined in a given set, we can simplify this:

var bs = your collection of EntityB
var dbSet = dbSet of type EntityA
var entities = dbSet.Where(m => m.Bs.Any(b =>
    bs.Any(b2 => b2.Foobar == b.Foobar).ToList();

So this will look through a collection of EntityA and will return any EntityA that has any EntityB with a Foobar equal to that of any in a given collection.

I would query from EntityA since you're getting a collection of EntityAs. But if you wanted to from EntityB you could do the following.

var entities = entityBSet.Where(m => 
    bs.Any(b => 
        b.Foobar == m.Foobar))
    .Select(m => m.A)
    .ToList();