在linq中对实体使用自定义方法 [英] Using custom methods in linq to entities
问题描述
我的数据库中有一个Person
表,该表具有NationalId
字段.
有什么方法可以使用Ef code first
和Linq to entities
甚至使用Ef code first
和Linq to entities
来加载所有带有NationalId
的人员,而不是将所有Person
都加载到内存中?
I have a Person
table in my database that has NationalId
field.
Is there any way to load all Persons with even NationalId
, using Ef code first
and Linq to entities
, without loading all Person
s to memory?
类似的东西
public bool IsEven(int number)
{
return number % 2 == 0;
}
var context = new MyContext();
var personsWithEvenNationalId = context.Persons
.Where(x=> IsEven(x.NationalId))
.ToList();
推荐答案
您必须进行内联检查
var personsWithEvenNationalId = context.Persons
.Where(x=> x.NationalId%2 == 0)
.ToList();
Linq to Entities基本上不知道如何将自定义方法转换为SQL.如果确实需要使用自定义方法,则必须使Persons枚举,然后使用自定义方法,即
Linq to Entities doesn't know how to translate your custom method into SQL basically. If you do need to use a custom method you would have to get Persons as enumerable and then use your custom method, i.e.
var personsWithEvenNationalId = context.Persons
.AsEnumerable()
.Where(x=> IsEven(x.NationalId))
.ToList();
但这并不理想,因为它将加载所有Person,然后在IsEven上进行过滤
But that's hardly ideal as it would load all Persons and then filter on IsEven
考虑一下它,如果不想每次都内联编写,也可以为IQueryable<Person>
创建扩展方法.在您构建Expression
Thinking about it you could also create an extension method for IQueryable<Person>
if you don't want to have to write it inline every time. Something like this where you build an Expression
public static IQueryable<Person> WhereEven(this IQueryable<Person> source, Expression<Func<Person, int>> property)
{
var expression = Expression.Equal(
Expression.Modulo(
property.Body,
Expression.Constant(2)),
Expression.Constant(0));
var methodCallExpression = Expression.Call(typeof (Queryable),
"where",
new Type[] {source.ElementType},
source.Expression,
Expression.Lambda<Func<Person, bool>>(expression, property.Parameters));
return source.Provider.CreateQuery<Person>(methodCallExpression);
}
并使用它:
context.Persons.WhereEven(x => x.NationalId).ToList();
这篇关于在linq中对实体使用自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!