实体框架Lambda谓词存储在var与关联

实体框架Lambda谓词存储在var与关联

本文介绍了实体框架Lambda谓词存储在var与关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用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与关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 13:39