У нас есть тестовый код Первый проект, где у нас есть два DbContexts, каждый из которых соответствует их собственной базе данных.Entity Framework. Множественные базы данных DbContext. MySQL. Code First
ApplicationDbContext:
using MultipleDbContext.Entities;
using MultipleDbContext.EntityConfigurations;
using System.Data.Entity;
namespace MultipleDbContext
{
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext() : base("ApplicationDBContext") {}
public DbSet<Application> Applications { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new ApplicationUserConfiguration());
modelBuilder.Configurations.Add(new ApplicationConfiguration());
}
}
}
ApplicationUserDbContext:
using MultipleDbContext.Entities;
using MultipleDbContext.EntityConfigurations;
using System.Data.Entity;
namespace MultipleDbContext
{
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class ApplicationUserDbContext : DbContext
{
public ApplicationUserDbContext() : base("UserDBContext") {
}
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ApplicationUserConfiguration());
}
}
}
Entity классы:
Применение:
using System.Collections.Generic;
namespace MultipleDbContext.Entities
{
public class Application
{
public int ApplicationID { get; set; }
public string ApplicationName { get; set; }
public int UserID { get; set; }
public virtual ApplicationUser PrimaryUser { get; set; }
}
}
И ApplicationUser
namespace MultipleDbContext.Entities
{
public class ApplicationUser
{
public int UserID { get; set; }
public string Name { get; set; }
}
}
Приложение имеет идентификатор пользователя FK, который он сопоставляет с нашим ApplicationUser.
using MultipleDbContext.Entities;
using System.Data.Entity.ModelConfiguration;
namespace MultipleDbContext.EntityConfigurations
{
public class ApplicationConfiguration : EntityTypeConfiguration<Application>
{
public ApplicationConfiguration()
{
HasKey(x => x.ApplicationID);
Property(x => x.ApplicationID).IsRequired();
Property(x => x.ApplicationName).IsRequired();
HasRequired(x => x.PrimaryUser).WithMany().HasForeignKey(x => x.UserID);
}
}
}
Когда я запускаю базу данных обновлений на ApplicationUser, она отлично работает. Но когда я пытаюсь запустить обновление базы данных по-ApplicationDbContext он бросает мне ошибку:
update-database -ConfigurationTypeName MultipleDbContext.Migrations.Configuration -verbose
Using StartUp project 'MultipleDbContext'.
Using NuGet project 'MultipleDbContext'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'test' (DataSource: test, Provider: MySql.Data.MySqlClient, Origin: Configuration).
Applying explicit migrations: [201611021534507_Initial].
Applying explicit migration: 201611021534507_Initial.
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Data.Entity.Migrations.DbMigrator.<ExecuteStatementsInternal>b__32(MigrationStatement s)
at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass30.<ExecuteStatements>b__2e()
at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute(Action operation)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Object reference not set to an instance of an object.
Что я делаю неправильно?