简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM