3

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?

ocuenca
  • 38,548
  • 11
  • 89
  • 102
Trevor Daniel
  • 3,785
  • 12
  • 53
  • 89

3 Answers3

4

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
ocuenca
  • 38,548
  • 11
  • 89
  • 102
  • I am getting the error: "Cannot implicitly convert type 'System.Data.Entity.Infrastructure.DbQuery' to 'System.Data.Entity.DbSet'. An explicit conversion exists (are you missing a cast?)" on the current.Include(include) part... :( – Trevor Daniel Aug 18 '16 at 14:22
  • That's make sense, use `IQueryable` type instead a `var` to save your query. That should solve the issue. – ocuenca Aug 18 '16 at 14:26
  • really sorry, now it's saying "System.Linq.IQueryable' does not contain a definition for 'Include' and no extension method 'Include' accepting a first argument of type 'System.Linq.IQueryable' could be found (are you missing a using directive or an assembly reference?)" – Trevor Daniel Aug 18 '16 at 14:27
  • 1
    Add `System.Data.Entity` namespace – ocuenca Aug 18 '16 at 14:28
0

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:

LINQ: Add RowNumber Column

Community
  • 1
  • 1
Monofuse
  • 735
  • 6
  • 14
0

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();
Matthew Thurston
  • 720
  • 5
  • 22