问题描述
我有一个使用EF6的通用存储库。该问题与需要包含的关联属性有关,即使它不应该。以下作品: IQueryable< User> dbQuery = _db.Set< User>();
return dbQuery.Where(x => x.Child.Name ==Foo)。ToList();
但是,以下内容不起作用:
Func< User,bool> filter = x => x.Child.Name ==Foo;
IQueryable< User> dbQuery = _db.Set< User>();
return dbQuery.Where(filter).ToList();
它在Child上引发Object Reference not set ...异常。
以下解决方法:
Func< User,bool> filter = x => x.Child.Name ==Foo;
IQueryable< User> dbQuery = _db.Set< User>();
dbQuery = dbQuery.Include(x => x.Child);
return dbQuery.Where(filter).ToList();
我不明白为什么这是必要的。任何人都知道如何解决这个问题,而不使用Include?
你应该使用表达式
让EF提供商解析您的查询。
将 Func< User,bool>
更改为 Expression&FunC< User,bool& ;>
I have a generic repository using EF6. The issue has to do with association properties requiring an "Include" even though it shouldn't. The following works:
IQueryable<User> dbQuery = _db.Set<User>();
return dbQuery.Where(x => x.Child.Name == "Foo").ToList();
However, the following does not work:
Func<User, bool> filter = x => x.Child.Name == "Foo";
IQueryable<User> dbQuery = _db.Set<User>();
return dbQuery.Where(filter).ToList();
It throws an "Object Reference not set..." exception on Child.
The following resolves it:
Func<User, bool> filter = x => x.Child.Name == "Foo";
IQueryable<User> dbQuery = _db.Set<User>();
dbQuery = dbQuery.Include(x => x.Child);
return dbQuery.Where(filter).ToList();
I don't understand why this is necessary though. Anyone know a way to resolve this without using the "Include"?
You are should use Expression
to let EF provider parse your query.
Change the Func<User, bool>
to Expression<Func<User, bool>>
这篇关于实体框架Lambda谓词存储在var与关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!