Reputation: 3974
Is it possible to specify "Includes" from a List please?
I have a list of possible sub tables to be included in:
List<string> includedTables
My current database call looks like this:
return db.SA_Items
.Where(x => x.LastUpdated > lastUpdated)
.Where(x => x.Active == true)
.OrderBy(x => x.ItemID)
.Skip(offset)
.Take(limit)
.ToList();
I would to somehow to a foreach string in the List and add a .Include(....)
to the database call...
Say, for example, if there were 2 strings in the list the code would be equivalent to this:
return db.SA_Items
.Include("first string in the list")
.Include("second string in the list")
.Where(x => x.LastUpdated > lastUpdated)
.Where(x => x.Active == true)
.OrderBy(x => x.ItemID)
.Skip(offset)
.Take(limit)
.ToList();
It's also possible that the List might be null.
Is it possible to do this dynamically somehow?
Can anyone give me any pointers please?
Upvotes: 3
Views: 3697
Reputation: 39386
Sure, you can build your query in several steps:
IQueryable<SA_Item> query=db.SA_Items;
if(includedTables!=null)
query = includedTables.Aggregate(query, (current, include) => current.Include(include));
query=query.Where(x => x.LastUpdated > lastUpdated)
.Where(x => x.Active == true)
.OrderBy(x => x.ItemID)
.Skip(offset)
.Take(limit);
return query.ToList();// Materialize your query
Upvotes: 4
Reputation: 760
you can do it with concat.
return db.SA_Items
.Concat(new string[] {"first string in the list", "second string in the list"})
.Where(x => x.LastUpdated > lastUpdated)
.Where(x => x.Active == true)
.OrderBy(x => x.ItemID)
.Skip(offset)
.Take(limit)
.ToList();
Upvotes: 0
Reputation: 827
You could do a similar thing which is happening in the following stackoverflow link, but replace the int index which has been added with your strings:
Upvotes: 0