简体   繁体   中英

Obtaining entities from DbSet from a list of matching objects

I'm using Entity Framework Core 6 and I want to find a series of entities in a DbSet . The entities I want to obtain are the ones match some properties in a list of input objects.

I've tried something like this:

public IEnumerable<MyEntity> FindEntities(IEnumerable<MyEntityDtos> entries)
{
    return dbContext.MyDbSet.Where(r => entries.Any(e => e.Prop1 == r.Prop1 && e.Prop2 == r.Prop2));            
}

But I get the classic EF Core exception saying that my LINQ cannot be translated to a database query (the problem in particular is the entries.Any(...) instruction)

I know I can just loop over the list of entries and obtain the entities one by one from the DbSet, but that is very slow, I was wondering if there was a more efficient way to do this in EF Core that I don't know about.

I think this should work:

public IEnumerable<MyEntity> FindEntities(IEnumerable<MyEntityDtos> entries)
{
    var props1=entries.Select(x=>x.Prop1).ToArray();
    var props2=entries.Select(x=>x.Prop2).ToArray();

    return dbContext.MyDbSet.Where(r => props1.Contains(r.Prop1) && props2.Contains(r.Prop2));            
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM