return 模型实体不存在的结果 - EF .net Core 3

return result with non-existing model entity - EF .net Core 3

我想 return SP 为当前模型实体中实际上不存在的列生成结果。 目前我只能 return 结果,这是当前模型之一。

   [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 是我的模型之一,因此结果的列应该与模型实体完全相同。 我如何添加自定义模型实体,以便 SP 将 return 结果与该自定义模型相匹配?

这意味着您的存储过程没有返回第 foo 列。 尝试:

  • 将您的列 Foo 添加到您的 SELECT 语句
  • 或使用 [NotMapped] 作为您的 Foo 列。此属性可用于我们不想在数据库中创建相应列的实体 class 的属性

您的存储过程 ioVouchers_sp_SalaryRanks 必须 return 可以映射到您的实体的结果 IoVouchersSalaryRank

如果它 return 是自定义结果,则必须以这种方式实现:

string query = "EXEC ioVouchers_sp_SalaryRanks";

var ranks = context.Set<CustomModel>().FromSqlRaw(query).ToList();

其中 CustomModel 是一个新实体,其中的属性可以映射到由您的 SP return编辑的列。所以,如果它 return 只有字符串类型的列 foo,它看起来像这样:

public class CustomModel
   {
       public string Foo{ get; set; }
   }

在 OnModelCreating 方法中将 CustomModel 添加到 dbcontext

        modelBuilder.Entity<CustomModel>().HasNoKey();

我有一篇博客post对此进行了解释,你可以在这里看看>> 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/SampleWithEFCore3.1

的示例