How to get ObjectResult from Entity Framework using a list of Identities

c# entity-framework

Question

I have a HashSet of Identity values that I need to use as the query values to return a ObjectResult from the Entity Framework

Here's the HashSet:

HashSet<int> officeIds = new HashSet<int>();

Here's the query that I'm trying to run more or less:

ObjectResult<FilingOffice> offices = ctx.FilingOffice.Where(office => office IN officeIds.ToList());

The "office => office IN officeIds.ToList()" part of the above is what I can't get to work and haven't found any samples on the web for returing objects given a list of primary keys.

ctx is the System.Data.Objects.ObjectContext

Accepted Answer

The examples others have given won't work in the Entity Framework today, because you can't mix client and serverside enumerations in LINQ 2 Entities.

Instead you need to build an OR expression, manually.

I run a series of EF Tips and this tip shows you how to build an OR expression up.

Hope this helps

Alex


Popular Answer

I have had similar issues a lot of times, another Stack Overflow question with good information is: Most efficient way to get multiple entities by primary key?

I prefer to use:

var entities = db.Entities.WhereIn(x => x.Id, ids);


Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why