C# 代码优先方法不创建表
我正在Core2.0中开发应用程序,并使用identity创建表。所以,当我运行应用程序时,数据库会自动创建。稍后,当我尝试运行迁移命令时,它不会创建表。 //达尔 下面是我运行的命令C# 代码优先方法不创建表,c#,entity-framework,asp.net-core-2.0,C#,Entity Framework,Asp.net Core 2.0,我正在Core2.0中开发应用程序,并使用identity创建表。所以,当我运行应用程序时,数据库会自动创建。稍后,当我尝试运行迁移命令时,它不会创建表。 //达尔 下面是我运行的命令 添加迁移20180921 更新数据库-详细 在控制台输出的末尾,它说 错误编号:2714,状态:6,类别:16 数据库中已经有一个名为“AspNetRoles”的对象。 还有一件事,当我删除数据库并运行应用程序时,所需的表会自动创建,而无需运行任何命令。 我错过了什么? 下面是Start.cs文件 publi
- 添加迁移20180921
- 更新数据库-详细
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(config =>
{
// Cookie settings
config.ExpireTimeSpan = TimeSpan.FromHours(2);
config.SlidingExpiration = true;
config.LoginPath = "/Account/Login";
config.LogoutPath = "/Account/LogOut";
config.AccessDeniedPath = "/Account/AccessDenied";
});
services.AddTransient<IAccountBAL, AccountBAL>();
services.AddSingleton<IConfiguration>(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAccountBAL _iAccountBAL)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
SeedDatabase.Initialize(app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope().ServiceProvider);
_iAccountBAL.CreateDefaultRoles().Wait();
_iAccountBAL.CreateSuperAdmin().Wait();
}
}
public static void Initialize(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetRequiredService<ApplicationDbContext>();
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
context.Database.EnsureCreated();
}
公共类启动
{
公共启动(IConfiguration配置,IHostingEnvironment环境)
{
配置=配置;
var builder=new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile(“appsettings.json”,可选:true,重载更改:true)
.AddJsonFile($“appsettings.{env.EnvironmentName}.json”,可选:true)
.AddenEnvironmentVariables();
Configuration=builder.Build();
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddMvc();
services.AddDbContext(选项=>
{
options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”);
});
服务.额外性()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(配置=>
{
//Cookie设置
config.ExpireTimeSpan=TimeSpan.FromHours(2);
config.SlidingExpiration=true;
config.LoginPath=“/Account/Login”;
config.LogoutPath=“/Account/LogOut”;
config.AccessDeniedPath=“/Account/AccessDenied”;
});
services.AddTransient();
services.AddSingleton(配置);
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序、IHostingEnvironment环境、IAccountBAL\u IAccountBAL)
{
if(env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
});
初始化(app.ApplicationServices.GetRequiredService().CreateScope().ServiceProvider);
_iAccountBAL.CreateDefaultRoles().Wait();
_iAccountBAL.CreateSuperAdmin().Wait();
}
}
公共静态无效初始化(IServiceProvider服务提供程序)
{
var context=serviceProvider.GetRequiredService();
var userManager=serviceProvider.GetRequiredService();
context.Database.recreated();
}
听起来您的应用程序在运行时正在应用迁移。请检查您的启动。cs
已迁移。如果应用程序拥有它,则需要将其删除,以便从PackageManager控制台运行迁移
private static void InitializeMigrations(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
MyDbContext dbContext = serviceScope.ServiceProvider.GetRequiredService<MyDbContext>();
dbContext.Database.Migrate();
}
}
私有静态无效初始化迁移(IAApplicationBuilder应用程序)
{
使用(var serviceScope=app.ApplicationServices.GetService().CreateScope())
{
MyDbContext=serviceScope.ServiceProvider.GetRequiredService();
dbContext.Database.Migrate();
}
}
从
确保上下文的数据库存在。如果存在,则不采取任何行动。如果不存在,则创建数据库及其所有架构。如果数据库存在,则不需要努力确保它与此上下文的模型兼容
请注意,此API不使用迁移来创建数据库。此外,以后无法使用迁移更新创建的数据库。如果您以关系数据库为目标并使用迁移,则可以使用
DbContext.database.Migrate()
方法来确保创建数据库并应用所有迁移。是否从代码运行迁移?请检查StartUp.cs是否有dbContext.Database.Migrate();运行迁移。上面的代码将运行迁移。如果应用程序有它,则需要将其删除,以便从package manager控制台运行迁移。将代码放入startup.cs中不会产生任何影响。我有另一个项目,他们也没有这样的初始化迁移是必需的。如果您希望我可以显示Startup.cs文件是的,请同时发布您的Startup.cs。我已输入Startup.cs文件最终我找到了解决方案。问题在于EntityFramework核心。删除数据库。运行程序。运行迁移命令(这将为AspNet和其他表创建迁移类)。注释所有代码inside Up()。现在取消注释required DbSet(在我的例子中是tblComment)属性。最后运行迁移命令。这将在数据库中成功创建表。
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(config =>
{
// Cookie settings
config.ExpireTimeSpan = TimeSpan.FromHours(2);
config.SlidingExpiration = true;
config.LoginPath = "/Account/Login";
config.LogoutPath = "/Account/LogOut";
config.AccessDeniedPath = "/Account/AccessDenied";
});
services.AddTransient<IAccountBAL, AccountBAL>();
services.AddSingleton<IConfiguration>(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAccountBAL _iAccountBAL)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
SeedDatabase.Initialize(app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope().ServiceProvider);
_iAccountBAL.CreateDefaultRoles().Wait();
_iAccountBAL.CreateSuperAdmin().Wait();
}
}
public static void Initialize(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetRequiredService<ApplicationDbContext>();
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
context.Database.EnsureCreated();
}
private static void InitializeMigrations(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
MyDbContext dbContext = serviceScope.ServiceProvider.GetRequiredService<MyDbContext>();
dbContext.Database.Migrate();
}
}