EFCore 从用于调用 SPROC 的数据模型中创建不必要的 Table,

EFCore Creates Unnecessary Table from Data Model used to call SPROC,

我在 MVC/Razor/WebAPI 应用程序中使用 Entity framework 核心从 asp.net 核心调用存储过程。 如果这是 nube,较新的开发人员深表歉意。我已经阅读了我能在 EF 的存储过程中找到的所有内容...

问题: 当我设置我的应用程序以调用存储过程时,EF Core 更新我的数据库(通过下一个迁移 I 运行)以根据我创建的模型创建一个空 table 以从存储过程检索输出。

示例: 我有一个 returns 两列

的存储过程
SELECT customerID, customerName from MyTable

我使用 [Keyless] 指令添加了一个简单的 POCO MyModel

namespace MyApp.Models 
{
    [Keyless]
    public class MyModel 
    {
        public int customerID { get; set; }
        public string customerName { get; set; }
    }
}

然后我在我的 ApplicationDBContext

中注册 class
public virtual DbSet<MyModel> MyModel { get; set; }

我现在可以使用以下方法从我的页面调用存储过程:

public List<MyModel> CustomerList { get; set; }

CustomerList = _context.MySproc
                     .FromSqlRaw($"MySproc")
                     .ToList();

当我下一个 运行 迁移时,EF 添加了迁移代码以根据我的模型创建一个 table,我认为我不需要它。

migrationBuilder.CreateTable(
     name: "VerifyEmailAndStripeCustomerID",
     columns: table => new
     {
     customerID = table.Column<int>(type: "int", nullable: false),
     customerName = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: true)
     },

如何在没有这种 table 创建行为的情况下调用存储过程?

灵感来自:

[Keyless] 仅指定没有主键的 table - 因此您需要在模型创建上更进一步,告诉它不要创建支持 table:

  1. 从您的上下文中删除 DbSet<MyModel> 属性(您可以保留它,但它会造成混淆,因为它没有 table... 支持)
  2. 在上下文的OnModelCreating中,注册and/or操作MyModel
modelBuilder.Entity<MyModel>().HasNoKey().ToView(null);
  1. 使用以下内容填充模型:
CustomerList = Context.Set<MyModel>().FromSql($"MySproc").ToList();