问题
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.
回答1:
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();
来源:https://stackoverflow.com/questions/23702682/how-to-query-for-all-entitya-that-contain-any-entityb-within-a-collection-of-ent