januszstabik
januszstabik

Reputation: 1162

How to append a where clause to an Entity Framework ObjectSet

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.

Upvotes: 2

Views: 20507

Answers (2)

Morteza Manavi
Morteza Manavi

Reputation: 33216

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();

Upvotes: 6

lcranf
lcranf

Reputation: 171

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;
}

Upvotes: 1

Related Questions