我正在使用Entity Framework Core(版本2.2.4)在ASP.NET Core应用程序上进行代码优先的迁移。
尝试在创建表时播种表,我的DbContext中包含以下代码:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Country>()
.HasData(SeedCountries());
}
SeedCountries正在返回要创建的国家对象数组,其中没有任何花哨的东西。
运行初始迁移时,发生以下错误:
System.NullReferenceException: Object reference not set to an instance of an object.
at MyApp.MyDbContext.SeedCountries()
当我删除HasData部分时,迁移运行正常并创建了数据库。 HasData调用在这里出了什么问题?
我已经在应用程序中移开了DbInitializer类,因为此DbContext在多个应用程序之间共享。我不希望该应用程序负责为数据库添加种子,我希望该代码位于我的EF类库中。
编辑: 我的DbContext驻留在单独的类库中。我还使用了实现IDesignTimeDbContextFactory接口的工厂。 当我在Web应用程序为活动项目的Package Manager控制台中添加迁移时,似乎工厂没有用于创建DbContext。相反,它试图实例化一个新的DbContext,实际上我没有无参数的构造函数,因为它需要一个我已在我的DI容器中注册的依赖项。 当我的Web应用程序是启动项目时,Add-Migration是否没有启动DbContextFactory?
PM> Add-Migration InitialMigration
System.MissingMethodException: No parameterless constructor defined for this object.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContextFromFactory(Type factory)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass14_0.<FindContextFactory>b__1()
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
No parameterless constructor defined for this object.