實體框架核心 - 遷移 - 沒有為此對象定義的無參數構造函數

asp.net-core c# entity-framework entity-framework-core

我正在使用Visual Studio 2017中最新的.Net Core和EF Core。我創建了一個模型,它運行良好。我已經做了一些修改,並在嘗試添加新遷移時收到以下錯誤:

Build succeeded.
  0 Warning(s)
  0 Error(s)

Time Elapsed 00:00:09.08
System.MissingMethodException: No parameterless constructor defined for this object.
  at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
  at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
  at System.Activator.CreateInstance(Type type, Boolean nonPublic)
  at System.Activator.CreateInstance(Type type)
  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_0.<FindContextTypes>b__3()
  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
  at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
  at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
  at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
  at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
No parameterless constructor defined for this object.

我已經比較了自上次簽入以來的代碼並且已經註釋掉了某些代碼塊以查看錯誤是否仍然存在以及我註釋掉了什麼,它仍然會失敗並出現相同的錯誤。

問題:有沒有辦法獲得有關WHAT類型沒有無參數構造函數的更詳細信息?或者甚至從VS中運行它並且可能得到一個斷點?

更新:根據一些評論,這裡是一些代碼。

對於DbContext覆蓋

public class AlmanacDb : IdentityDbContext<ApplicationUser, ApplicationRole, int> {

  private readonly ILogger logger;

  public AlmanacDb(DbContextOptions<AlmanacDb> options, ILoggerFactory loggerFactory) : base(options) {
    this.logger = loggerFactory.CreateLogger<AlmanacDb>();
  }

  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
    optionsBuilder.UseSqlServer("Server=.\\SQLExpress;Database=Almanac;Trusted_Connection=True;MultipleActiveResultSets=True;");
  }

  ...
}

我有一個IDbContextFactory但它沒有在任何地方引用,沒有引用工作。根據第二條評論中提供的鏈接,不確定這是否存在問題。如果內存服務,只要IDbContextFactory在解決方案中,它應該找到它?

public class AlmanacDbFactory : IDbContextFactory<AlmanacDb> {

  private IConfigurationRoot configuration;
  private readonly ILoggerFactory loggerFactory;

  public AlmanacDbFactory(ILoggerFactory loggerFactory) {
    var builder = new ConfigurationBuilder()
     .SetBasePath(System.AppContext.BaseDirectory)
     .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

    this.configuration = builder.Build();
    this.loggerFactory = loggerFactory;
  }

  public AlmanacDb Create(DbContextFactoryOptions options) {
    var optionsBuilder = new DbContextOptionsBuilder<AlmanacDb>();
    optionsBuilder.UseSqlServer(
      configuration.GetConnectionString("AlmanacSQL"), m => { m.EnableRetryOnFailure(); }
    );

    return new AlmanacDb(optionsBuilder.Options, loggerFactory);
  }
}

我的Startup.cs

public void ConfigureServices(IServiceCollection services) {
  try {
    services.AddDbContext<AlmanacDb>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("AlmanacSQL"))
    );
    services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

    services.AddIdentity<ApplicationUser, ApplicationRole>()
      .AddEntityFrameworkStores<AlmanacDb, int>()
      .AddDefaultTokenProviders();

    services.AddScoped<SignInManager<ApplicationUser>, AvantiaSignInManager<ApplicationUser>>();

    services.AddAuthorization(x => {
      x.AddPolicy("EmployeeOnly", p => p.RequireClaim("EmployeeNumber"));
    });

    services.AddMvc();
  } catch (Exception e) {
    Console.WriteLine(e.ToString());
    throw;
  }
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, AlmanacDb context) {
  ... // Nothing actually touches the AlmanacDb within this code so I left it out
}

更新2:Solutiuon看到我正在學習ASP.Net Core我正在閱讀大量網站(包括docs.microsoft.com),我在上面提到了IDbContextFactory代碼。我從我的代碼中刪除了它,錯誤消失了,所有內容都構建並創建了遷移。

我打算將@alessalessio標記為答案,因為我假設(還沒有測試過)在AlmanacDbFactory構造函數中取出ILoggerFactory loggerFactory依賴項也可以。

一般承認的答案

設計時工具嘗試自動查找應用程序如何創建DbContext類型的實例。如果EF無法找到初始化DbContext的合適方法,則可能會遇到此錯誤。

選項:1-創建無參數構造函數

  public AlmanacDb() { }
  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  {           
       optionsBuilder.UseSqlServer(_connString);
  }

  private readonly string _connString = "<your conn string>";

2-

public AlmanacDb Create()
{
     var optionsBuilder = new DbContextOptionsBuilder<AlmanacDb>();
     optionsBuilder.UseSqlServer(connectionString);

     return new AlmanacDb(optionsBuilder.Options);
}

https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext


熱門答案

我遇到過同樣的問題。當我將ApplicationUser的imeplementation更改為User with Guid Id時,我的問題就出現了。

public class User : IdentityUser<Guid>

首先,我開始得到一些瘋狂的錯誤,並在設置我的DbContext後:

public class NgSchoolsContext : IdentityDbContext<User, IdentityRole<Guid>, Guid>

我開始得到“無參數構造函數”錯誤。最終修復它的是改變Startup中的角色配置:

services.AddIdentityCore<User>() .AddEntityFrameworkStores<NgSchoolsContext>() .AddRoles<IdentityRole<Guid>>() .AddDefaultTokenProviders();

注意IdentityRole部分。你不需要實現一件事,就這樣說吧。它應該開箱即用。然而!!您的遷移將失敗,您將不得不從頭開始重建您的數據庫。實體無法處理他的所有主鍵從字符串(或其他)轉到Guid並且無法更新數據庫的事實。嗯,這至少更容易解決。刪除數據庫,刪除所有遷移,添加遷移(新的初始)和更新數據庫。如果是正常的錯誤消息,這將是如此容易。



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow