2016-11-07 50 views
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 }); 
     } 
    } 
} 

回答

0

这是因为你的DbSet性质实际上不是性能:) ...他们是各个领域。使他们属性与吸气剂和二传手和