带有自定义方法的 LINQ to Entities Where 子句

LINQ to Entities Where clause with custom method

我正在使用 Entity Framework Core (2.0),我有以下疑问。

我不确定执行此操作时会发生什么:

context.Customers.Where(c => MyCustomMethod(c));

bool MyCustomMethod(Customer c) 
{
    return c.Name.StartsWith("Something");
}

翻译成 SQL 是否没有问题?

和写作有区别吗:

context.Customers.Where(c => c.StartsWith("Something"));

简而言之,我能否将对 Where 子句的验证包装在一个方法中?它会破坏对 SQL 的翻译吗?

不,您不能在 EF LINQ 查询中调用您的自定义方法,因为 EF 将无法生成该方法的表达式树,因此它无法将其转换为 SQL。

有关表达式树的详细信息,请参阅 link

如果您需要从方法中获取字符串,您可以像这样编写相同的查询

from customer in contetx.Customer 
                let str = GetString()
                where Name.Any(c=> c.StartsWith(str) )
                select customer;

string GetString() 
{
    return "Something";
}

我不知道这有什么用,但这可以实现