[英]return result with non-existing model entity - EF .net Core 3
我想通過 SP 返回當前 model 實體中實際上不存在的列的結果。 目前我只能返回當前模型之一的結果。
[HttpGet]
public async Task<ActionResult> getAllSalaryRanks()
{
HttpResponseMessage response = new HttpResponseMessage();
using(db963Context context = new db963Context())
{
var ranks = context.IoVouchersSalaryRanks.FromSqlRaw("EXEC ioVouchers_sp_SalaryRanks").ToList();
return Ok(ranks);
}
}
在上面的示例中,我將收到一個異常消息: The required column 'foo' was not present in the results of a 'FromSql' operation.
基本上IoVouchersSalaryRanks
是我的模型之一,因此結果的列應該與 model 實體完全相同。 如何添加自定義 model 實體,以便 SP 返回與該自定義 model 匹配的結果?
這意味着您的存儲過程不會返回foo
列。 嘗試:
Foo
添加到您的SELECT
語句中Foo
列使用[NotMapped]
。 此屬性可用於我們不想在數據庫中創建相應列的實體 class 的屬性 您的存儲過程ioVouchers_sp_SalaryRanks
必須返回一個可以映射到您的實體IoVouchersSalaryRank
的結果
如果它返回自定義結果,則必須以這種方式實現:
string query = "EXEC ioVouchers_sp_SalaryRanks";
var ranks = context.Set<CustomModel>().FromSqlRaw(query).ToList();
其中 CustomModel 是一個新實體,其中的屬性可以映射到您的 SP 返回的列。 因此,如果它只返回類型為 string 的列 foo,它將如下所示:
public class CustomModel
{
public string Foo{ get; set; }
}
在 OnModelCreating 方法中將 CustomModel 添加到 dbcontext
modelBuilder.Entity<CustomModel>().HasNoKey();
我有一篇博客文章對此進行了解釋,您可以在這里查看>> https://mohamedsahbi.com/2019/05/22/raw-queries-with-entity-framework-core/
更新:我的博客與 EF Core 2.1 相關。 所以,我剛剛更新了使用 EF Core3.1 的答案。您還可以找到一個 GitHub 存儲庫,其中包含 EF Core 3.1 https 的示例://github.com/MohamedSahbi/RawQueryWithEFCore/tree/master/SampleWithEFCore/Sample。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.