EF Core:方法“ProcessModelFinalized”没有实现

Mau*_*tti 6 c# entity-framework-core asp.net-core

我在尝试使用实体框架核心获取 DbContext 对象中 DbSet 的信息时遇到错误。

我的 DbContext 对象看起来像这样:

public class CatalogueContext : DbContext
{
    public DbSet<ConnectorCatalogueItemConv> CatalogueItemConvs { get; set; }

    public CatalogueContext(DbContextOptions<CatalogueContext> options)
        : base(options)
    {

    }

    public CatalogueContext()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

我试图通过调用一个接收泛型类型 T 的方法来实例化上下文,该类型可能是 DbContext 的子类:

public T GetContext<T>() where T: DbContext, new()
{
    var optionsBuilder = new DbContextOptionsBuilder<T>();
    var connectionString = Configuration.GetConnectionString(ExternalTablesKey);
    optionsBuilder.UseSqlServer(connectionString);
    return Activator.CreateInstance(typeof(T), optionsBuilder.Options) as T;
}
Run Code Online (Sandbox Code Playgroud)

通过使用 Microsoft.Extensions.Configuration 正确获取连接字符串,因此问题不存在。

最后,我调用此方法并尝试获取声明如下的 DbSet 上的任何记录:

 public void SomeMethod()
 {
     using (var db = this.GetContext<CatalogueContext>())
     {
         var val = db.CatalogueItemConvs.ToList(); //Here is where I get the error below.
     }
 }
Run Code Online (Sandbox Code Playgroud)

显示的错误说:

来自程序集“Microsoft.EntityFrameworkCore.SqlServer, Version=3.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60”的“Microsoft.EntityFrameworkCore.Metadata.Conventions.SqlServerValueGenerationStrategyConvention”类型中的方法“ProcessModelFinalized”没有实现。

我到处搜索,但似乎有关此错误的信息很少。有什么想法吗?

编辑 1: 我的解决方案包括版本 3.0.0.0 中的 Microsoft.EntityFrameworkCore.SqlServer

编辑 2: 根据要求,我编辑了代码以仅包含一个实体及其类声明。此时没有映射。

public class ConnectorCatalogueItemConv
{
    public string CodConnector { get; set; }
    public string CodCatalogue { get; set; }
    public string CodItemCia { get; set; }
    public string CodItemInbk { get; set; }
    public bool Defaultvalue { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

编辑 3: 如何在 EF Core 中实例化 DbContext

小智 13

我也遇到了同样的错误,我已经将我的 Microsoft.EntityFrameworkCore.SqlServer 和 Microsoft.EntityFrameworkCore.Tools 更新到了 5.0 版,然后它工作了,

  • 我在已经安装了 3.x 版本的“Microsoft.EntityFrameworkCore.InMemory”的测试项目中安装 5.0 版本的“Microsoft.EntityFrameworkCore.*”包时遇到了此错误。这为我解决了这个问题。 (2认同)

小智 5

我的两点意见:如果您希望使用 .NET core 3.0 版本而不是升级到 .Net 5.0,那么您需要做的就是确保上面提到的所有包都使用版本 3.xx 而不是 5。 xx 我注意到,当您尝试构建身份页面时,它会安装该软件包的 5.xx 版本,因为它是最新的,而不是检查软件包 .net core 版本并安装适当的版本。