asp.net - 如何在 Entity Framework 核心中调用标量函数

标签 asp.net entity-framework asp.net-core entity-framework-core

this article之后,我试图使用Entity Framework Core在我的应用程序中调用内部SQL函数

我在上下文中创建了静态方法,如下所示:

public class DbContext : DbContext
{
    public DbContext(DbContextOptions<DbContext> options) : base(options)
    {
    }

    [DbFunction("FN_ENCRYPT", "DBO")]
    public static string FN_ENCRYPT(string ENC)
    {
        throw new NotImplementedException();
    }
}

在此之后,我对如何调用感到有些困惑,因此我尝试了这种方式(当然,因为它是静态方法):
public string Encript(string word)
{
    return DbContext.FN_ENCRYPT(word);
}

但猜猜怎么了?我收到一个“不错”的NotImplementedException :)

有人可以帮我吗?

提前致谢

最佳答案

使用调用本身会引发异常,因为它实际上会执行C#代码。建议抛出异常的原因正是这样,以避免意外使用,即通过直接调用它。该签名将由给定的LINQ提供程序 解释,并转换为正确的SQL语句。

在MS EF Core Database scalar function mapping中:

they can be used in LINQ queries and translated to SQL



这是一个工作示例:

模型和DbContext
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime DOB  { get; set; }
}

public class MyDbContext:DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options):base(options)
    { }

    public DbSet<Employee> Employees { get; set; }

    [DbFunction("CalculateAge", "dbo")]
    public static int CalculateAge(DateTime dob)
    {
        throw new NotImplementedException();
    }
}

和使用
public IActionResult GetAge(int employeeId)
    {
        var query = _context.Employees
                .Where(x => x.Id == employeeId)
                .Select(d =>new
                { 
                    Name=d.Name,
                    DOB=d.DOB,
                    Age= MyDbContext.CalculateAge(d.DOB)
                }).ToList();
        return Json(query);
    }

结果

enter image description here

关于asp.net - 如何在 Entity Framework 核心中调用标量函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58713900/

相关文章:

javascript - 第一个函数执行完毕后如何调用第二个函数?

c# - 无法安装 System.Data.SqlClient

c# - Onclientclick如何使用Javascript更改表格的背景颜色

c# - Entity Framework : Create database column without property in model class

c# - Entity Framework 内存使用

c# - Entity Framework - 将数据库字段映射到 uint

javascript - Jquery Cycle2 幻灯片 - 从服务器加载图像,ASP .NET

asp.net - 如何在Docker dotnet框架镜像上使用dotnet核心

c# - 使用区域和 Controller 名称进行路由(asp.net core)

asp.net-core - 使用 OpenIdDict 时不允许 'offline_access' 范围