已解析的数据库上下文产生null DbSet
本文关键字:null DbSet 上下文 数据库 | 更新日期: 2023-09-27 18:16:51
我的项目中有3个组件:MyApp.Core
, MyApp.Infrastructure
, MyApp.Web
。
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 });
}
}
}
这是因为你的DbSet属性实际上不是属性:)…它们是田地。让它们具有getter和setter以及