'TContext'上找不到無參數構造函數

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

我不清楚錯誤發生的原因。當我第一次構建我的項目時,遷移和更新數據庫命令運行正常,但在應用程序中進行了少量更改後,我收到了此錯誤 。左右浮動唯一的解決辦法是這樣

public class BloggingContextFactory : IDbContextFactory<BloggingContext>
{
    public BloggingContext Create()
    {
        var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
        optionsBuilder.UseSqlite("Data Source=blog.db");

        return new BloggingContext(optionsBuilder.Options);
    }
}

我的DbContext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IApplicationDbContext
{
    public DbSet<ApplicationUserCode> ApplicationUserCodes { get; set; }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }
}

它適用於我,但連接字符串在類中是硬編碼的,這對我來說不合適。關於為什麼這個錯誤一次沒有發生以及之後發生的任何澄清都非常受歡迎,也是比在課堂中嵌入連接字符串更優雅的解決方案。

一般承認的答案

你有這個嗎?

public class BloggingContext : DbContext
{
    public BloggingContext(){          // << The reason....

    }
    public BloggingContext(DbContextOptions<BloggingContext> options)
         : base(options)
    { }

   public DbSet<Blog> Blogs { get; set; }
}

另一個原因是它看到OnModelCreating(ModelBuilder builder){}覆蓋而沒有base.OnModelCreating(builder);在方法本身頂部的OnModelCreating(){}方法內部調用。告訴我一個循環,為什麼...然後我嘗試了一些東西,低,看到它是一個簡單的包含無參數構造函數,它看起來是罪魁禍首。

 protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);   //<< Absolutely required at the top.
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);

編輯

//Startup.cs ConfigureServices(IServiceCollection服務)

 services.AddDbContext<ApplicationDbContext>(options =>
      options.UseSqlite(Configuration.GetConnectionString("SqliteConnection")));

//appsettings.json

{
  "ConnectionStrings": {
   "DefaultConnection": "Data Source=(LocalDb)\\MssqlLocalDb;Initial        Catalog=PilotSystemCore;Integrated Security=True",
"SqliteConnection" :  "Data Source=SqliteDbName.db"
 },
 "Logging": {
    "IncludeScopes": false,
     "LogLevel": {
         "Default": "Debug",
         "System": "Information",
         "Microsoft": "Information"
   }
 }
}

注意:如果您之前使用SqlServer進行了任何遷移,則生成的項長期有效,可以重新進行遷移。



Related

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