Asp.net
如何在 Entity Framework Core 中呼叫標量函式
在這篇文章之後,我嘗試使用 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 數據庫標量函式映射中:
它們可用於 LINQ 查詢並轉換為 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); }結果
