开发者

How to append a where clause to an Entity Framework ObjectSet

开发者 https://www.devze.com 2023-01-22 22:37 出处:网络
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:

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开发者_JAVA百科.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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号