我有这个扩展方法在我的。net代码检查字符串是否为:
public static bool IsSomething(this string text)
{
var isNothing = string.IsNullOrEmpty(text) || string.IsNullOrWhiteSpace(text);
return !isNothing;
}
然而,我不能在我的EF Core查询中使用它:
dbset.Where(i => i.Title.IsSomething()); // throws non-translatable error
我知道我可以把我的查询重写为:
dbset.Where(i => i.Title != null && i.Title.Trim() != ""); // this works, but it's too verbose
但我真的不想写那么久non-descriptive代码。
我怎么能有IsSomething
是可翻译的SQL服务器?
只用IsNullOrWhiteSpace
;它做IsNullOrEmpty
做的:
返回
true
如果值参数是null或空,或者价值由专门的空白字符。——IsNullOrWhiteSpace
被EF Core映射到SQL
@value IS NULL OR LTRIM(RTRIM(@value)) = N''
注意,在EF Core 6中,这改为@value IS NULL OR value= N''
-同样的处理;sql忽略字符串comp
中的尾随空格这意味着你的IsSomething
方法实际上是!IsNullOrWhiteSpace
,如果你使用它,EF会翻译它。
无法将此方法转换为SQL Server。但是,您可以使用返回Expression的方法。例如:
public static Expression<Func<Student, bool>> IsSomething()
{
return (s) => string.IsNullOrEmpty(s.FirstName) || string.IsNullOrWhiteSpace(s.FirstName);
}
通常,在使用方法之前应该调用AsEnumerable:
dbset.AsEnumerable().Where(i => i.Title.IsSomething());
但是它会从数据库中加载所有实体。