1
我在我的项目中有3个组件:MyApp.Core
,MyApp.Infrastructure
,MyApp.Web
。已解决的数据库上下文产生空DbSet
MyApp.Core
包含数据库模型/实体,MyApp.Infrastructure
包含数据库上下文和迁移,而MyApp.Web
包含Startup
类。
该数据库是使用代码第一个EF创建的,它存在(我选中)。
我所注册的数据库上下文我Startup
类的ConfigureServices
方法:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<MyAppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<Employee, IdentityRole>()
.AddEntityFrameworkStores<KinderGardenDbContext>()
.AddDefaultTokenProviders();
...
}
我想用我的静态方法MyApp.Infrastructure.MyAppContextSeed.Seed()
种子我的数据库。所以,我在Configure
方法的末尾添加方法:
...
MyAppDbContextSeed.Seed(app.ApplicationServices).Wait();
}
在上述方法中,我解决了数据库上下文:
public static async Task Seed(IServiceProvider services)
{
...
using (var context = services.GetRequiredService<MyAppDbContext>())
using (var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>())
using (var userManager = services.GetRequiredService<UserManager<Employee>>())
{
if (!await context.Companies.AnyAsync())
{
...
}
}
}
在上面的if
声明,Companies
为空。
而且,这里是我的数据库上下文类:
namespace MyApp.Infrastructure.EntityFramework
{
public class MyAppDbContext : IdentityDbContext<Employee>
{
public DbSet<Company> Companies;
public DbSet<Person> Persons;
public DbSet<Employee> Employees;
public DbSet<KeyCard> KeyCards;
public DbSet<KeyRequestForm> KeyRequestForms;
public KinderGardenDbContext(DbContextOptions<KinderGardenDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Company>().ToTable("Company");
builder.Entity<Person>().ToTable("Person");
builder.Entity<Employee>().ToTable("Employee");
builder.Entity<KeyCard>().ToTable("KeyCard");
builder.Entity<KeyRequestForm>().ToTable("KeyRequestForm");
builder.Entity<KeyCardKeyRequestForm>().ToTable("KeyCardKeyRequestForm");
builder.Entity<KeyCardKeyRequestForm>()
.HasKey(c => new { c.KeyCardId, c.KeyRequestFormId });
}
}
}