问题
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.
回答1:
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();
回答2:
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;
}
来源:https://stackoverflow.com/questions/4079691/how-to-append-a-where-clause-to-an-entity-framework-objectset