gpt4 book ai didi

c# - 代码优先方法不创建表

转载 作者:太空宇宙 更新时间:2023-11-03 14:49:22 26 4
gpt4 key购买 nike

我正在 Core 2.0 中开发应用程序并使用身份创建表。所以当我运行应用程序时,数据库会自动创建。稍后当我尝试运行迁移命令时,它不会创建表。//DAL

public class ApplicationDbContext:IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
{

}
public DbSet<tblContact> tblContacts { get; set; }

//protected override void OnModelCreating(ModelBuilder builder)
//{
// base.OnModelCreating(builder);
//}
}

//需要的表类

 public partial class tblContact
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ContactId { get; set; }
public string PhoneNumber { get; set; }
}

以下是我运行的命令

  • 添加迁移 20180921
  • 更新数据库-详细

在控制台输出的末尾,它说错误编号:2714,状态:6,类别:16数据库中已有名为“AspNetRoles”的对象。

还有一件事,当我删除数据库并运行应用程序时,需要的表会自动创建,而无需运行任何命令。我在这里缺少什么?以下是 Start.cs 文件

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();
}

最佳答案

听起来您的应用程序在运行时应用了迁移。请检查您的 Startup.cs 是否已迁移。如果您的应用程序有它,您需要将其删除,以便从包管理器控制台运行迁移。

private static void InitializeMigrations(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
MyDbContext dbContext = serviceScope.ServiceProvider.GetRequiredService<MyDbContext>();
dbContext.Database.Migrate();

}
}

来自 MSDN

确保上下文的数据库存在。如果存在,则不采取任何操作。如果它不存在,则创建数据库及其所有模式。如果数据库存在,则不会努力确保它与此上下文的模型兼容。

请注意,此 API 不使用迁移来创建数据库。此外,创建的数据库以后无法使用迁移进行更新。如果您的目标是关系数据库并使用迁移,则可以使用 DbContext.Database.Migrate() 方法来确保创建数据库并应用所有迁移。

关于c# - 代码优先方法不创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52441330/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com