![](/img/trans.png)
[英]Best practice calling scalar functions with Entity Framework Core (2.1)
[英]500 Error calling scalar database function from .net core 2.1
我試圖從.NET Core 2.1 Web API調用數據庫中的標量函數,以獲取一名雇員的主管; 我數據庫中的函數期望將雇員ID作為輸入,並返回主管的ID。 它工作得很好,叫做dbo.fn_GetDirectorID
。
我想在Web API中創建一個端點來調用此函數以獲取directorID
然后將該控制器的雇員對象發送回我的客戶端。 所以我一直在尋找在線資源,我發現這很可能,所以讓我們嘗試一下,所以我按照他們的教程進行操作,現在在我的上下文中有一個GetDirectorID
數據庫功能,例如所描述的鏈接
[DbFunction("fn_GetDirectorID", "dbo")]
public static int GetDirectorID(int id)
{
throw new NotImplementedException();
}
然后在我的控制器中,我要做這樣的事情
[HttpGet("GetDirector/{id}")]
public async Task<IActionResult> GetDirector([FromRoute] int id)
{
var directorID = KPContext.GetDirectorID(id);
var director = await _context.Employees.FindAsync(directorID);
if (director == null)
{
return NotFound();
}
return Ok(director);
}
但是當我打電話給我時,我拋出錯誤是因為我要拋出新的NotIMplementedException
,但是我不確定在這里做什么,因為本教程說這應該調用您的函數並起作用。 我也做了
int directorID = KPContext.GetDirectorID(id)
有人可以幫忙嗎? 我將不勝感激。
我也試過了
[HttpGet("GetDirector/{id}")]
public async Task<IActionResult> GetDirector([FromRoute] int id)
{
var director = await _context.Employees.FindAsync(KPContext.GetDirectorID(id));
if (director == null )
{
return NotFound();
}
return Ok(director);
}
這樣的標量函數只能在LINQ to Entities查詢中使用(無法在客戶端執行,必須是SQL查詢的一部分)。
這意味着您不能使用FindAsync
,而應使用FirstOrDefaultAsync
或SingleOrDefaultAsync
:
var director = await _context.Employees
.SingleOrDefaultAsync(e => e.Id == KPContext.GetDirectorID(id));
與FindAsync
,這也具有優勢,您可以渴望加載( Include
/ ThenInclude
)相關數據。
還請注意(鏈接中未提及),如果標量函數在目標DbContext
派生類之外的其他類中定義,則不會自動注冊,因此您需要在派生的DbContext
添加類似的DbContext
類OnModelCreating
重寫(當然,如果它不是KPContext
類):
modelBuilder.HasDbFunction(() => KPContext.GetDirectorID(default(int)));
有關更多信息,請參見數據庫標量函數映射文檔。
我會嘗試使用linq查詢,因為我認為尚不支持純EF。
[HttpGet("GetDirector/{id}")]
public async Task<IActionResult> GetDirector([FromRoute] int id)
{
var director = from p in _context.Employees where p.EmployeeId == KPContext.GetDirectorID(id) select p;
if (director == null )
{
return NotFound();
}
return Ok(director);
}
這應該為您提供所需的東西,讓我知道它是否對您有用!! 歡呼,祝你有美好的一天。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.