从Entity Framework 6.1.1升级到6.1.3后出错

时间:2015-10-30 08:13:24

标签: c# entity-framework entity-framework-6

我们正在使用Entity Framework 6来操作我们的数据库。当我们使用EF 6.1.1时,它可以正常工作,从不会遇到任何错误。最近,我们决定将我们的实体框架升级到最新版本6.1.3。升级非常简单,但在将引用升级到6.1.3后会遇到以下错误。这是异常的callstack。

System.TypeInitializationException: The type initializer for 'IvyBridge.Services.Core.Implements.AdminService' threw an exception. ---> System.Data.SqlClient.SqlException: There is already an object named 'Accounts' in the database.
Result1 StackTrace: 
  at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
  at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
  at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
  at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
  at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
  at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
  at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
  at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
  at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
  at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
  at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
  at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
  at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
  at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable`1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
  at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
  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.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
  at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
  at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.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.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
  at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
  at System.Data.Entity.Migrations.DbMigrator.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.DbMigrator.Update(String targetMigration)
  at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
  at System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState)
  at System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)
  at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
  at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
  at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
  at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
  at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
  at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
  at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
  at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
  at System.Data.Entity.Internal.InternalContext.ForceOSpaceLoadingForKnownEntityTypes()
  at System.Data.Entity.DbContext.System.Data.Entity.Infrastructure.IObjectContextAdapter.get_ObjectContext()
  at IvyBridge.Database.DatabaseContext..ctor() in d:\Project\TradingPlatform\Source\DataBase\MyDataBase\MyDataBase\DatabaseContext.cs:line 17
  at IvyBridge.Services.Core.Helpers.BrokerRuleCache.LoadBrokerRules() in d:\Project\TradingPlatform\Source\Services\IvyBridge.Services.Core\Helpers\BrokerRuleCache.cs:line 57
  at IvyBridge.Services.Core.Implements.AdminService..cctor() in d:\Project\TradingPlatform\Source\Services\IvyBridge.Services.Core\Implements\AdminService.cs:line 109

我们的代码如下:

     public class DatabaseContext : DbContext
     {
         public DatabaseContext()
         {
             ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized +=
            (sender, e) => DateTimeKindAttribute.Apply(e.Entity);
         }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
        }
        ...
     }

如何使用它:

    public static void LoadBrokerRules()
    {
        using (var context = new DatabaseContext())
        {
            try
            {
                var operation = new BrokerRuleOperation(context);
                var result = operation.GetAllRules();
                ...
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("{0}\r\n{1}", ex.Message, ex.StackTrace);
                throw;
            }
        }
    }

BrokerRuleOperation类:

    private DatabaseContext db;

    public BrokerRuleOperation(DatabaseContext db)
    {
        this.db = db ?? new DatabaseContext();
    }

    public ICollection<BrokerRule> GetAllRules()
    {
        return db.BrokerRules.ToList();
    }

我们的代码可能存在哪些问题?

0 个答案:

没有答案