我不清楚错误发生的原因。当我第一次使用我的项目时,迁移和更新数据库命令运行正常,但在应用程序中进行了少量更改后,我得到了this error。浮动的唯一解决方案是this:
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);
}
}
它适用于我,但连接字符串在类中是硬编码的,这对我来说不合适。关于为什么这个错误一次没有发生以及之后发生的任何澄清都非常受欢迎,也是比在课堂中嵌入连接字符串更优雅的解决方案。
答案 0 :(得分:3)
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)
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进行过任何迁移,则生成的项长期有效,可以重新进行迁移。