loyalflow
loyalflow

Reputation: 14919

Return list of models passing in a List of ids using repository pattern

I'm using the repository with the Unit of work pattern based on:

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

Their Get function looks like:

 public virtual IEnumerable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "")

Now I want to get a List of rows as an output.

The query will also have a WHERE IN clause like:

SELEcT *
FROM ...
   INNER JOIN ...
WHERE homeId in (select homeId ....)

I have the list of home ids:

List<int> homeIdList = ...

How can I build this query using the Get method above?

Get(x => x.Id == cityId, includeProperties: "CityBlock, CityBlock.Homes")

The above is a query that is similiar to what I want, but I want to limit the Homes to be where their id is in the List homeIdList.

Possible?

Upvotes: 1

Views: 4000

Answers (1)

Ashkan
Ashkan

Reputation: 2390

Use List's Contains method which will is translated to sql's in operator. I Suggest that you try to get a list of Homes with their CityBlock and City property included, then you can use linq to get all cities:

var repository = new GenericRepository<Home>();
var homes = repository.Get(home => homeIdList.Contains(home.Id), 
                            includeProperties: "CityBlock, CityBlock.City")
                            .ToList();
var cities = homes.Select(h => h.CityBlock.City).Distinct().ToList();

Hope this helps.

Upvotes: 1

Related Questions