2

I would like to append a set of conditional where clauses onto the end of an ObjectSet. However, the clauses do not get executed and instead the original query is run, for example:

using (Entities context = new Entities()){
var q = context.AuditLogs;
q.Where(o => o.WebsiteId == 1);
}

The where clause is not executed and the full result set is returned I could instead use IQueryAble as in:

var q = context.AuditLogs.AsQueryable();
q = q.Where(o => o.WebsiteId == 1);

However this loses me the power of being able to use .Include to eager load my related entities.

januszstabik
  • 1,152
  • 5
  • 16
  • 30

2 Answers2

6

No, it won't. at any point before executing the query, you would still be able to cast it back to ObjectQuery<T> and invoke methods like Include on it:

var query = context.AuditLogs.AsQueryable();
query = query.Where(o => o.WebsiteId == 1);
var auditLog = ((ObjectQuery<AuditLog>)query).Include("yourNavPropertyName")
                                             .ToList();

If your intention is to build up a criteria incrementally, then the other option would be to leverage EntitySQL with QueryBuilder methods:

var query = context.AuditLogs.Where("it.WebsiteId = 1");
query = query.Where("...");
var auditLog = query.Include("yourNavPropertyName")
                    .ToList();
Morteza Manavi
  • 33,026
  • 6
  • 100
  • 83
  • to avoid the cast at the end, can you do something like context.AuditLogs.Include("navProp").AsQueryable(); ? Or will that still execute the entire result set then filter it down client-side? – JoeBrockhaus Oct 17 '12 at 20:41
1

Just some good old fashioned linq would suffice here. Assuming you had a property named SiteOwner you could accomplish what your trying to do with the below query

using (Entities context = new Entities()){
  var webSites = from sites in context.AuditLogs.Include("SiteOwner")
                 where sites.WebSiteId == 1
                 select sites;
}
lcranf
  • 171
  • 1
  • 1
  • 6
  • Sorry that wasn't what i was looking for, include only works when using ObjectSet whereas a I needed a combination of functionality between IQueryable and Object set as in Morteza's answer – januszstabik Nov 03 '10 at 08:37