entity-framework - 模拟 DbFunctions.Like

标签 entity-framework entity-framework-6 nunit moq

我尝试通过遵循 this ticket 中最流行的答案来模拟 DbFunctions.Like 函数并像这样创建它的本地实现:

public static class DbFunctions
{
    [DbFunction("Edm", "TruncateTime")]
    public static DateTime? TruncateTime(DateTime? dateValue)
        => dateValue?.Date;

    [DbFunction("Edm", "Like")]
    public static bool Like(string searchString, string likeExpression)
        => Regex.IsMatch(searchString, $"^{likeExpression.Replace("%", ".*")}$");

    [DbFunction("Edm", "Right")]
    public static string Right(string stringArgument, long? length)
        => stringArgument.Substring(stringArgument.Length - ((int?) length ?? 0));
}

并在查询中使用此函数代替 System.Entity.DbFunctions:

var query = Context.Items.AsQueryable();

if (!string.IsNullOrWhiteSpace(Number))
{
     var valuesToSearch = Number.Split(';')
                .Select(number => number.Trim())
                .AsEnumerable();

     query = query.Where(x => valuesToSearch.Any(v => DbFunctions.Like(x.Number, v)));
}

它适用于例如“TruncateTime”或“Right”函数。

当我调试解决方案时,会调用函数的 sql 版本,而当我运行单元测试时,会调用本地版本并通过测试。

当谈到“喜欢”时,我仍然收到 NotSupportedException: Exception thrown

是否不可能以与其他系统函数相同的方式模拟 DbFunctions.Like?

我使用的是 EF6 v6.4.4、Moq v4.14.1 和 nUnit v3.12.0。

最佳答案

DbFunctions.Like 没有 DbFunctionAttribute,因此不能以这种方式进行模拟。作为解决方法,您可以使用 SqlFunctions.PatIndex。 PatIndex 将返回给定模式在字符串中第一次出现的位置,如果根本没有出现,则返回 0。

[DbFunction("SqlServer", "PATINDEX")]
public static int? Like(string searchString, string likeExpression)
    => Regex.IsMatch(searchString, $"^{likeExpression.Replace("%", ".*")}$") ? 1 : 0;

query = query.Where(x => valuesToSearch.Any(v => DbFunctions.Like(x.Number, v) > 0));

可以为你工作。但就可读性而言,它不是很好。

关于entity-framework - 模拟 DbFunctions.Like,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63559408/

相关文章:

c# - 设置 WHERE 条件以在 ExecuteSqlCommand() 中使用 Ids.Contains()

entity-framework-6 - 增加 EF6 中的命令超时

c# - Selenium 2.0 WebDriver 和 :hover pseudoclass 的解决方法

nunit - 在.net core 2.2项目运行 "workers"时如何将 "dotnet test"参数传递给nunit runner

c# - EF6中找不到用于插入记录的AddObject方法

unit-testing - 为什么不在单元测试中访问数据库?

c# - 更智能的 Entity Framework Codefirst 流畅的 API

c# - 基类不能修改的类的基类方法?

c# - 接受过滤条件和要过滤的属性的通用 Linq to Entities 过滤方法

c# - 在单个上下文中使用多个模式的 Entity Framework 和迁移