我想在類中回傳帶有自定義訊息的 https 錯誤狀態代碼。但是,每當我嘗試這樣做時,它都會說它無法從 IResult 轉換為我的模型類員工。在創建處理 sql 邏輯的類之前,我在 program.cs 檔案中將其作為以下內容,當我輸入資料庫中不存在的值時,該檔案按預期作業。
app.MapGet("/employee/{id}", (ApplicationDbContext db, int id) =>
{
var employee = db.Employee.Find(id);
if (employee == null)
return Results.NotFound("Employee not found");
return Results.Ok(employee);
});
現在創建一個單獨的類以將所有邏輯放在一個檔案中,我在 program.cs 檔案中有以下內容,在單獨的檔案中有邏輯。
app.MapGet("/employee/{id}", (IDataRepository dr, int id) =>
{
return dr.GetEmployee(id);
});
現在在單獨的檔案中:
public Employee GetEmployee(int id)
{
var employee = _db.Employee.Find(id);
if (employee == null)
{
return Results.NotFound("Employee not found!");
}
return employee;
}
它建議我的模特班,員工。當我輸入一個知道它在資料庫中不存在的 id 時,它給了我一個轉換錯誤,說不能轉換兩者。任何建議將不勝感激。
uj5u.com熱心網友回復:
如果要拆分代碼,建議您將 nofound 方法保留在端點檔案中。實際上,此邏輯與您的 GetEmployee 方法無關。以后如果你想在代碼的另一部分重用GetEmployee邏輯,notfound方法會給你帶來麻煩。
我的意思是就職責而言,您的方法 GetEmployee 正在檢索員工并回傳狀態代碼(與員工無關)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/449829.html
