在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语句。 they can be used in LINQ queries and translated to SQL
在MS EF Core Database scalar function mapping中:
这是一个工作示例:
模型和DbContextpublic 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);
}
结果
关于asp.net - 如何在 Entity Framework 核心中调用标量函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58713900/