我想在启动期间使用实体框架创建一个表。我在单独的项目中有上下文。
方法中的Startup.cs :配置(IApplicationBuilder应用程序)
try
{
using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
scope.ServiceProvider.GetRequiredService<MyContext>().Database.Migrate();
}
}
catch (Exception ex)
{
throw;
}
这段代码没有创建表格。
然而,当我试图通过创建迁移时
dotnet ef migrations add AddTable_CLient -c MyContext
。该表正在创建,但
scope.ServiceProvider.GetRequiredService<MyContext>().Database.Migrate();
不会为我创建表格。它显示表已经创建。
public class DesignTimeDbContextFactory: IDesignTimeDbContextFactory<VerittyContext>
{
public MyContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<MyContext>();
builder.UseSqlServer("Server=localhost;Database=ClientManagement;Trusted_Connection=True;MultipleActiveResultSets=true",
optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(MyContext).GetTypeInfo().Assembly.GetName().Name));
return new VerittyContext(builder.Options);
}
}
MyContext.cs
public DbSet<Company> Company { get; set; }
public DbSet<CompanyContact> CompanyContact { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
relationship.DeleteBehavior = DeleteBehavior.Restrict;
}
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Company>();
modelBuilder.Entity<CompanyContact>();
}
我希望在将表添加到Context类时自动创建表。我不想手动添加迁移。使用下面的代码不是自动将表添加到数据库的方法吗?
using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
scope.ServiceProvider.GetRequiredService<MyContext>().Database.Migrate();
}
请帮助。