LINQ to Entities Where子句与自定义方法
问题描述:
我正在使用实体框架核心(2.0),我有以下疑问。LINQ to Entities Where子句与自定义方法
我不知道我这样做的时候会发生什么:
context.Customers.Where(c => MyCustomMethod(c));
bool MyCustomMethod(Customer c)
{
return c.Name.StartsWith("Something");
}
是否翻译没有问题到SQL?
它比写作不同:
context.Customers.Where(c => c.StartsWith("Something"));
总之,我就能换一个方法内我对那里化酶验证?它打破了对SQL的翻译吗?
答
不,您不能在EF LINQ查询中调用您的自定义方法,因为EF将无法生成该方法的表达式树,因此无法将其转换为SQL。
有关表达式树的详细信息,请参考以下链接 -
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/
答
,如果你需要从方法的字符串,你可以这样写
from customer in contetx.Customer
let str = GetString()
where Name.Any(c=> c.StartsWith(str))
select customer;
string GetString()
{
return "Something";
}
我硝基甲苯知道该查询是有帮助的,但是这可以实现
你试过了吗?结果是什么? – Flater
这是行不通的,因为EF不知道如何处理你的'MyCustomMethod' – DavidG
我觉得你可以在这里面调用这个内部过程,在这种情况下 –