简体   繁体   中英

There is already an object named 'Employee' in the database

I try to update my database, but I have this error:

There is already an object named 'Employee' in the database.

This is my last migration file:

 public partial class explain : DbMigration
    {
        public override void Up()
        {
            DropForeignKey("dbo.Employee", "Person_PersonId", "dbo.Person");
            DropForeignKey("dbo.Receptionist", "PersonId", "dbo.Employee");
            DropIndex("dbo.Employee", new[] { "Person_PersonId" });
            CreateTable(
                "dbo.Employee",
                c => new
                    {
                        PersonId = c.Int(nullable: false),
                        Receptionist_PersonId = c.Int(),
                        Salary = c.Int(nullable: false),
                        Hiredate = c.DateTime(nullable: false),
                        isManager = c.Boolean(nullable: false),
                    })
                .PrimaryKey(t => t.PersonId)
                .ForeignKey("dbo.Person", t => t.PersonId)
                .ForeignKey("dbo.Receptionist", t => t.Receptionist_PersonId)
                .Index(t => t.PersonId)
                .Index(t => t.Receptionist_PersonId);

            AddForeignKey("dbo.Receptionist", "PersonId", "dbo.Employee", "PersonId");
            DropTable("dbo.Employee");
        }

        public override void Down()
        {
            CreateTable(
                "dbo.Employee",
                c => new
                    {
                        PersonId = c.Int(nullable: false),
                        Salary = c.Int(nullable: false),
                        Hiredate = c.DateTime(nullable: false),
                        isManager = c.Boolean(nullable: false),
                        Person_PersonId = c.Int(nullable: false),
                    })
                .PrimaryKey(t => t.PersonId);

            DropForeignKey("dbo.Employee", "Receptionist_PersonId", "dbo.Receptionist");
            DropForeignKey("dbo.Receptionist", "PersonId", "dbo.Employee");
            DropForeignKey("dbo.Employee", "PersonId", "dbo.Person");
            DropIndex("dbo.Employee", new[] { "Receptionist_PersonId" });
            DropIndex("dbo.Employee", new[] { "PersonId" });
            DropTable("dbo.Employee");
            CreateIndex("dbo.Employee", "Person_PersonId");
            AddForeignKey("dbo.Receptionist", "PersonId", "dbo.Employee", "PersonId");
            AddForeignKey("dbo.Employee", "Person_PersonId", "dbo.Person", "PersonId");
        }
    }

Employee.cs model

public class Employee : Person
    {
        public Employee()
        {
            EmployeeSchedule = new HashSet<EmployeeSchedule>();
            Vacation = new HashSet<Vacation>();
        }

        [Required]
        [Display(Name = "Wynagrodzenie")]
        public int Salary { get; set; }

        [Required]
        [Display(Name = "Data zatrudnienia")]
        public DateTime Hiredate { get; set; }

        [Display(Name = "Kierownik")]
        public bool isManager { get; set; }

        public virtual ICollection<EmployeeSchedule> EmployeeSchedule { get; set; }

        public virtual Lifeguard Lifeguard { get; set; }

        public virtual Receptionist Receptionist { get; set; }

        public virtual Trainer Trainer { get; set; }
        public virtual ICollection<Vacation> Vacation { get; set; }
    }

Person.cs

public abstract class Person
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int PersonId { get; set; }

        [Required]
        public long Pesel { get; set; }

        [Required]
        [StringLength(30, ErrorMessage = "Imię nie może zawierać więcej niż 30 znaków.")]
        [Display(Name = "Imię")]
        public string FirstName { get; set; }

        [Required]
        [StringLength(60, ErrorMessage = "Nazwisko nie może zawierać wiecej niż 60 znaków.")]
        [Display(Name = "Nazwisko")]
        public string LastName { get; set; }

        [Required]
        [EmailAddress(ErrorMessage = "Błędny format adresu e-mail.")]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        [Display(Name = "Data urodzenia")]
        public DateTime DateOfBirth  { get; set; }
        [NotMapped]
        public int age;
        [NotMapped]
        public int Age
        {
            get
            {
                DateTime today = DateTime.Today;
                age = today.Year - DateOfBirth.Year;
                if (DateOfBirth > today.AddYears(-age))
                {
                    age--;
                }
                return age;
            }
        }

        [NotMapped]
        [Display(Name="Imię i Nazwisko")]
        public string FullName
        {
            get
            {
                return FirstName + " " + LastName;
            }
        }

    }

Stack Trace:

[SqlException (0x80131904): There is already an object named 'Employee' in the database.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action 1 wrapCloseInAction) +2418102
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction) +2418102
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction) +2418102
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction) +5694456 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +285

System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +3731
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) +959
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource 1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +272
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +280
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext
1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +272
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +280
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext
1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +272
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +280
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext
1 c) +36

System.Data.Entity.Infrastructure.Interception.InternalDispatcher 1.Dispatch(TTarget target, Func 3 operation, TInterceptionContext interceptionContext, Action 3 executing, Action 3 executed) +138
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext) +476
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery() +177 System.Data.Entity.Migrations.DbMigrator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext) +194
System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext) +62
System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable 1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext) +113
System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable
1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext) +113
System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable
1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext) +113
System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable
1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext) +110

System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction(IEnumerable 1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext) +172
System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable
1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext) +172
System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable
1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext) +172
System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable
1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext) +429

System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable 1 migrationStatements, DbConnection connection) +646
System.Data.Entity.Migrations.<>c__DisplayClass30.<ExecuteStatements>b__2e() +66 System.Data.Entity.SqlServer.<>c__DisplayClass1.<Execute>b__0() +34 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func
1 migrationStatements, DbConnection connection) +646
System.Data.Entity.Migrations.<>c__DisplayClass30.<ExecuteStatements>b__2e() +66 System.Data.Entity.SqlServer.<>c__DisplayClass1.<Execute>b__0() +34 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func
1 migrationStatements, DbConnection connection) +646
System.Data.Entity.Migrations.<>c__DisplayClass30.<ExecuteStatements>b__2e() +66 System.Data.Entity.SqlServer.<>c__DisplayClass1.<Execute>b__0() +34 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func
1 operation) +251

System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation) +196
System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable 1 migrationStatements, DbTransaction existingTransaction) +327
System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable
1 migrationStatements, DbTransaction existingTransaction) +327
System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable
1 migrationStatements, DbTransaction existingTransaction) +327
System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable
1 migrationStatements) +39

System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable 1 migrationStatements) +42
System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable
1 migrationStatements) +42
System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable
1 migrationStatements) +42
System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable
1 operations, IEnumerable 1 systemOperations, Boolean downgrading, Boolean auto) +1372 System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration) +783
System.Data.Entity.Migrations.Infrastructure.MigratorBase.ApplyMigration(DbMigration migration, DbMigration lastMigration) +56
System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable
1 systemOperations, Boolean downgrading, Boolean auto) +1372 System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration) +783
System.Data.Entity.Migrations.Infrastructure.MigratorBase.ApplyMigration(DbMigration migration, DbMigration lastMigration) +56
System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable
1 systemOperations, Boolean downgrading, Boolean auto) +1372 System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration) +783
System.Data.Entity.Migrations.Infrastructure.MigratorBase.ApplyMigration(DbMigration migration, DbMigration lastMigration) +56
System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable
1 pendingMigrations, String targetMigrationId, String lastMigrationId) +192 System.Data.Entity.Migrations.Infrastructure.MigratorBase.Upgrade(IEnumerable 1 pendingMigrations, String targetMigrationId, String lastMigrationId) +59 System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration) +888
System.Data.Entity.Migrations.<>c__DisplayClassc.<Update>b__b() +38
System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +516
System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +42
System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +136
System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update() +33 System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func
1 pendingMigrations, String targetMigrationId, String lastMigrationId) +59 System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration) +888
System.Data.Entity.Migrations.<>c__DisplayClassc.<Update>b__b() +38
System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +516
System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +42
System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +136
System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update() +33 System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func
1 pendingMigrations, String targetMigrationId, String lastMigrationId) +59 System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration) +888
System.Data.Entity.Migrations.<>c__DisplayClassc.<Update>b__b() +38
System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +516
System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +42
System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +136
System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update() +33 System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func
3 createMigrator, ObjectContext objectContext) +175 System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState) +150

System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +444
System.Data.Entity.DropCreateDatabaseAlways 1.InitializeDatabase(TContext context) +158
System.Data.Entity.Internal.<>c__DisplayClassf
1.InitializeDatabase(TContext context) +158
System.Data.Entity.Internal.<>c__DisplayClassf
1.InitializeDatabase(TContext context) +158
System.Data.Entity.Internal.<>c__DisplayClassf
1.b__e() +165 System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +110

System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +660 System.Data.Entity.Internal.LazyInternalContext.b__4(InternalContext c) +31
System.Data.Entity.Internal.RetryAction 1.PerformAction(TInput input) +143 System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action 1 action) +292
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() +123 System.Data.Entity.Internal.InternalContext.Initialize() +42 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +39
System.Data.Entity.Internal.Linq.InternalSet 1.Initialize() +137
System.Data.Entity.Internal.Linq.InternalSet
1.Initialize() +137
System.Data.Entity.Internal.Linq.InternalSet
1.Initialize() +137
System.Data.Entity.Internal.Linq.InternalSet
1.get_InternalContext() +38 System.Data.Entity.Internal.Linq.InternalSet 1.FindAsync(CancellationToken cancellationToken, Object[] keyValues) +58
System.Data.Entity.DbSet
1.FindAsync(CancellationToken cancellationToken, Object[] keyValues) +58
System.Data.Entity.DbSet
1.FindAsync(CancellationToken cancellationToken, Object[] keyValues) +58
System.Data.Entity.DbSet
1.FindAsync(CancellationToken cancellationToken, Object[] keyValues) +70

System.Data.Entity.DbSet 1.FindAsync(Object[] keyValues) +69
Microsoft.AspNet.Identity.EntityFramework.EntityStore
1.FindAsync(Object[] keyValues) +69
Microsoft.AspNet.Identity.EntityFramework.EntityStore
1.FindAsync(Object[] keyValues) +69
Microsoft.AspNet.Identity.EntityFramework.EntityStore
1.GetByIdAsync(Object id) +104

Microsoft.AspNet.Identity.EntityFramework.d__6c.MoveNext() +275 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter 1.GetResult() +28 Microsoft.AspNet.Identity.CultureAwaiter 1.GetResult() +123 Microsoft.AspNet.Identity.Owin.<b__1>d__4.MoveNext() +1519 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 Microsoft.Owin.Security.Cookies.d__2.MoveNext() +3729 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +28 Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +810 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +427 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 Microsoft.AspNet.Identity.Owin.d__0.MoveNext() +641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 Microsoft.AspNet.Identity.Owin.d__0.MoveNext() +641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 Microsoft.AspNet.Identity.Owin.d__0.MoveNext() +641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 Microsoft.AspNet.Identity.Owin.d__0.MoveNext() +641 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext() +287 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__2.MoveNext() +272 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +26 Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow() +33 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +150
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +42
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +380 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Try moving the DropTable statement up before the Create statement in the migration. This way you drop the existing Employee table before creating a new one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM