我想做那样的事情;
Context.Users.Include("Addresses", a => a.IsRowDeleted == false).FirstOrDefault(u => u.UserId == 5);
我的意思是;我想过滤包含的实体但不总是,它也必须是可选的。
最佳解决方案是什么?请帮帮我,
答案 0 :(得分:3)
您无法在EF中过滤预先加载的数据。 Include
操作不支持过滤或排序。
您必须使用投影到自定义类型(或匿名类型):
var query = from u in context.Users
where u.UserId == 5
select new UserFiltered
{
User = u,
Addresses = u.Addresses.Where(a => !a.IsRowDeleted)
};
UserFiltered u = query.FirstOrDefault();
或者您必须将查询分成两个独立的查询并使用显式加载:
context.ContextOptions.LazyLoadingEnabled = false;
var user = context.Users.FirstOrDefault(u => u.UserId == 5);
((EntityCollection<Address>)user.Addresses)
.CreateSourceQuery()
.Where(a => !a.IsRowDeleted)
.Execute();
或者你可以简单地使用两个查询:
var user = context.Users.FirstOrDefault(u => u.UserId == 5);
var addresses = context.Addresses.Where(a => a.User.UserId == 5 && !a.IsRowDeleted).ToList();
答案 1 :(得分:2)
你的意思是(警告:未经测试的代码):
Context.Users.SingleOrDefault(u => u.Addresses.Where(a => a.IsRowDeleted == false).Count > 0) && u.UserId == 5);