sql - 在 Linq 中使用 ToList() 时避免使用 NVARCHAR
问题描述
我在 Column(TypeName) 设置为 VARCHAR 的类中有一个属性,但是当 linq 使用 ToList() 时,linq 生成的 SQL 会转换为 NVARCHAR。有没有办法避免调用 ToList() 方法时发生的 nvarchar 转换?
var codes = xyz.Where(x => x.IsValid).Select(x => x.Code.ToLower()).ToList();
requests = requests.Where(p => codes.Contains(p.Type.ToLower()));
Property(c => c.Type).HasColumnType("varchar").HasMaxLength(3).IsFixedLength();
如上所示,虽然 Type 属性的列类型设置为 VARCHAR,但 linq 在使用 ToList() 时使用 NVARCHAR。
解决方案
您可以构建自己的谓词:
public static class PredicateBuilder
{
private static readonly MethodInfo asNonUnicodeMethodInfo =
typeof(EntityFunctions).GetMethod("AsNonUnicode");
private static readonly MethodInfo stringEqualityMethodInfo =
typeof(string).GetMethod("op_Equality");
public static Expression<Func<TEntity, bool>> ContainsNonUnicodeString<TEntity>(
IEnumerable<string> source,
Expression<Func<TEntity, string>> expression)
{
if (source == null) throw new ArgumentNullException("source");
if (expression == null) throw new ArgumentNullException("expression");
Expression predicate = null;
foreach (string value in source)
{
var fragment = Expression.Equal(
expression.Body,
Expression.Call(null,
asNonUnicodeMethodInfo,
Expression.Constant(value, typeof(string))),
false,
stringEqualityMethodInfo);
if (predicate == null)
{
predicate = fragment;
}
else
{
predicate = Expression.OrElse(predicate, fragment);
}
}
return Expression.Lambda<Func<TEntity, bool>>(predicate,
((LambdaExpression)expression).Parameters);
}
}
推荐阅读
- datetime - 我们可以在 dart/flutter 中格式化没有 Intl Package 的 DateTime 吗?
- go - 为什么会有这样的结果?
- css - 对其他样式组件的引用不起作用
- java - 如何让 IntelliJ 使用它构建的 Maven 配置文件运行 Spring Boot 应用程序?
- javascript - react.js npm包无法解析
- javascript - 执行不会超过第二次 fetch 调用(与 Gatsby 相关的东西)
- python-3.x - 以固定大小保存绘图
- r - 在 ggplot2 中向 DotPlot 添加均值和胡须
- r - 将具有来自全局环境的信息的函数应用于列表
- css - 如何改变 Ant design Tooltip 宽度