데이터베이스에 이미 이름이 지정된 개체가 있습니다.
패키지 관리자 콘솔에서 Update-Database가 실패했습니다. Entity Framework 6.x 및 코드 우선 접근 방식을 사용했습니다. 오류는
"데이터베이스에 'AboutUs'라는 개체가 이미 있습니다."
이 문제를 어떻게 해결할 수 있습니까?
internal sealed class Configuration
: DbMigrationsConfiguration<Jahan.Blog.Web.Mvc.Models.JahanBlogDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = false;
}
protected override void Seed(Jahan.Blog.Web.Mvc.Models.JahanBlogDbContext context)
{
}
}
내 DbContext는 다음과 같습니다.
public class JahanBlogDbContext : IdentityDbContext<User, Role, int, UserLogin, UserRole, UserClaim>
{
public JahanBlogDbContext()
: base("name=JahanBlogDbConnectionString")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<JahanBlogDbContext>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Comment>().HasRequired(t => t.Article).WithMany(t => t.Comments).HasForeignKey(d => d.ArticleId).WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>().ToTable("User");
modelBuilder.Entity<Role>().ToTable("Role");
modelBuilder.Entity<UserRole>().ToTable("UserRole");
modelBuilder.Entity<UserLogin>().ToTable("UserLogin");
modelBuilder.Entity<UserClaim>().ToTable("UserClaim");
}
public virtual DbSet<Article> Articles { get; set; }
public virtual DbSet<ArticleLike> ArticleLikes { get; set; }
public virtual DbSet<ArticleTag> ArticleTags { get; set; }
public virtual DbSet<AttachmentFile> AttachmentFiles { get; set; }
public virtual DbSet<Comment> Comments { get; set; }
public virtual DbSet<CommentLike> CommentLikes { get; set; }
public virtual DbSet<CommentReply> CommentReplies { get; set; }
public virtual DbSet<ContactUs> ContactUs { get; set; }
public virtual DbSet<Project> Projects { get; set; }
public virtual DbSet<ProjectState> ProjectStates { get; set; }
public virtual DbSet<ProjectTag> ProjectTags { get; set; }
public virtual DbSet<Rating> Ratings { get; set; }
public virtual DbSet<Tag> Tags { get; set; }
public virtual DbSet<AboutUs> AboutUs { get; set; }
}
패키지 관리 콘솔 :
PM> update-database -verbose -force
Using StartUp project 'Jahan.Blog.Web.Mvc'.
Using NuGet project 'Jahan.Blog.Web.Mvc'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'Jahan-Blog' (DataSource: (local), Provider: System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
Applying automatic migration: 201410101740197_AutomaticMigration.
CREATE TABLE [dbo].[AboutUs] (
[Id] [int] NOT NULL IDENTITY,
[Description] [nvarchar](max),
[IsActive] [bit] NOT NULL,
[CreatedDate] [datetime],
[ModifiedDate] [datetime],
CONSTRAINT [PK_dbo.AboutUs] PRIMARY KEY ([Id])
)
System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'AboutUs' in the database.
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(DbTransaction transaction, MigrationStatement migrationStatement, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbTransaction transaction, 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.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument 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.Infrastructure.MigratorLoggingDecorator.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.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)
ClientConnectionId:88b66414-8776-45cd-a211-e81b2711c94b
There is already an object named 'AboutUs' in the database.
PM>
마이그레이션 프로세스에 문제가있는 것 같습니다. "Package Manager Console"에서 add-migration 명령을 실행하십시오.
추가 마이그레이션 초기 -IgnoreChanges
일부 변경을 수행 한 다음 "초기"파일에서 데이터베이스를 업데이트합니다.
Update-Database -verbose
편집 : -IgnoreChanges는 EF6에 있지만 EF Core에는 없습니다. 해결 방법은 다음과 같습니다. https://stackoverflow.com/a/43687656/495455
Maybe you have changed the namespace in your project!
There is a table in your data base called dbo.__MigrationHistory
. The table has a column called ContextKey
.
The value of this column is based on your namespace
. for example is "DataAccess.Migrations.Configuration
".
When you change the namespace, it causes duplicate table names with different namespaces.
So, after you change namespace in code side, change the namespace in this table in database, too, (for all rows).
For example, if you change the namespace to EFDataAccess
, then you should change the values of ContextKey
column in dbo.__MigrationHistory
to "EFDataAccess.Migrations.Configuration
".
Then in code side, in Tools => Package Manager Console, use the update-database
command.
Another option instead of changing the context value in the database is to hard code the context value in your code to the old namespace value. This is possible by inheriting DbMigrationsConfiguration<YourDbContext>
and in the constructor just assign the old context value to ContextKey
, than inherit from MigrateDatabaseToLatestVersion<YourDbContext, YourDbMigrationConfiguration>
and leave that class empty. The last thing to do is call Database.SetInitializer(new YourDbInitializer());
in your DbContext in a static constructor.
I hope your problem will be fixed.
"There is already an object named 'AboutUs' in the database."
This exception tells you that somebody has added an object named 'AboutUs' to the database already.
AutomaticMigrationsEnabled = true;
can lead to it since data base versions are not controlled by you in this case. In order to avoid unpredictable migrations and make sure that every developer on the team works with the same data base structure I suggest you set AutomaticMigrationsEnabled = false;
.
Automatic migrations and Coded migrations can live alongside if you are very careful and the only one developer on a project.
There is a quote from Automatic Code First Migrations post on Data Developer Center:
Automatic Migrations allows you to use Code First Migrations without having a code file in your project for each change you make. Not all changes can be applied automatically - for example column renames require the use of a code-based migration.
Recommendation for Team Environments
You can intersperse automatic and code-based migrations but this is not recommended in team development scenarios. If you are part of a team of developers that use source control you should either use purely automatic migrations or purely code-based migrations. Given the limitations of automatic migrations we recommend using code-based migrations in team environments.
In my case, my EFMigrationsHistory
table was emptied (somehow) and when trying to run update-database
I would get:
There is already an object named 'AspNetUsers' in the database
After seeing the table had been emptied it made sense that it was trying to rerun the initial migration and trying to recreate the tables.
To fix this problem I added rows into my EFMigrationsHistory
table. 1 row for each migration that I knew the database was up to date with.
A row will have 2 columns: MigrationId
and ProductVersion
MigrationId
is the name of your migration file. Example: 20170628112345_Initial
ProductVersion
is the ef version you're running. You can find this by typing Get-Package
into the Package Manager Console and looking for your ef package.
Hope this is helpful for someone.
In my case I had re-named the assembly that contained the code-first entity framework model. Although the actual schema hadn't changed at all the migrations table called
dbo.__MigrationHistory
contains a list of already performed migrations based on the old assembly name. I updated the old name in the migrations table to match the new and the migration then worked again.
Make sure your solutions startup project has the correct connectionstring in the config file. Or set the -StartUpProjectName parameter when executing the update-database command. The -StartUpProjectName parameter specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used.
Here is a link for ef-migration command references http://coding.abel.nu/2012/03/ef-migrations-command-reference/
Note: not recommended solution. but quick fix in some cases.
For me, dbo._MigrationHistory
in production database missed migration records during publish process, but development database had all migration records.
If you are sure that production db has same-and-newest schema compared to dev db, copy all migration records to production db can solve the issue.
You can do in VisualStudio solely.
- Open 'SQL Server Object Explorer' panel > right-click
dbo._MigrationHistory
table in source(in my case dev db) database > Click "Data Comparison..." menu. - Then, Data Comparison wizard poped up, select target database(in my case production db) and click Next.
- A few seconds later, it will show some records only in source database. just click 'Update Target' button.
- In browser, hit refresh button and see the error message gone.
Note that, again, it is not recommended in complex and serious project. Use this only you have problem during ASP.Net or EntityFramework learning.
I had same problem and after three hour struggling I find out what's going on
In my case, when I wanted to migrate for the first time in up()
method, the default code wants to create the tables that already existed so I got same error as you
To solve it, just delete those code and write want you want. For example, I wanted to add a column so i just write
migrationBuilder.AddColumn<string>(
name: "fieldName",
table: "tableName",
nullable: true);
Delete rows from dbo_MigrationHistory table or delete the table and run
update-database -verbose
It will run all the migrations in your project one by one
In my case, the issue was in Seeder. I was calling _ctx.Database.EnsureCreated() inside of it and as far as I understood, the update database command has successfully executed, but then seeder tried to create database "second" time.
How to address:
- Do nut run update, just start application and call EnsureCreated(). Database will be created/updated
- Comment out or remove seeder.
Another edge-case EF Core scenario.
Check you have a Migrations/YOURNAMEContextModelSnapshot.cs file.
as detailed in - https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#create-a-migration
If you have tried to manually re-create your database by deleting migration.cs files, be careful that your Migrations/*ContextModelSnapshot.cs file still exists.
Without it, your subsequent migrations have no snapshot on which to create the required differences and your new migrations files will look like they are re-creating everything again from scratch, you will then get the existing table error as above.
Simply execute command update-migration -Script. This generate new *.sql script which include all DB changes included in migration. In the end of code are insert commands something like this: INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion]) you can simply run this all INSERT and DB will be synchronized
After more than an hour of not getting any results I tried another approach, not using migrations but I did a schema compare.
In Visual Studio -> Tools -> SQL Server -> New Schema Comparison
First I created a new completely new database with EF migrations. Than I did a compare, comparing the new database with the one I wanted to update. Finally generated a migration script, and I could perform a schema update.
In my case (want to reset and get a fresh database),
First I has got the error message : There is already an object named 'TABLENAME' in the database.
and I saw, a little bit before:
"Applying migration '20111111111111_InitialCreate'.
Failed executing DbCommand (16ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE MYFIRSTTABLENAME"
My database was created, but no record in migrations history.
I drop all tables except dbo.__MigrationsHistory
MigrationsHistory was empty.
Run dotnet ef database update -c StudyContext --verbose
(--verbose just for fun)
and got Done.
I faced the same bug as below. Then I fixed it as below:
- Check current databases in your project:
dotnet ef migrations list
- If the newest is what you've added, then remove it:
dotnet ef migrations remove
- Guarantee outputs of this database must be deteled in source code: .cs/.Designer.cs files
4.Now it is fine. Try to re-add: dotnet ef migrations add [new_dbo_name]
5.Finally, try to update again, in arrangement base on migration list:
dotnet ef database update [First]
dotnet ef database update [Second]
- ...
dotnet ef database update [new_dbo_name]
Hope it is helpful for you. ^^
same happened with me.. Problem was that Actually i deleted my Database table MoviesCast
and made new table and problem was that my last migration was trying to induce the deleted table MoviesCast
in the database. I Solved it by simply removing all the content of last migration and simply ran Up() & down() method
public override void Up()
{
}
public override void Down()
{
}
then updated the database and simply add new migration
In migration file check the public override void Up() method. May be you are trying to create a new db object which is already in database. So, you need to drop this object/table before creation of the db object. Just do like bellow-
DropTable("dbo.ABC");
CreateTable(
"dbo.ABC",
c => new
{
Id = c.Int(nullable: false, identity: true),
..
}
And now run your migration Update-Database -TargetMigration: "2016_YourMigration"
참고URL : https://stackoverflow.com/questions/26305273/there-is-already-an-object-named-in-the-database
'programing' 카테고리의 다른 글
과거 커밋을 어떻게 쉽게 수정할 수 있습니까? (0) | 2020.08.20 |
---|---|
jQuery를 사용하여 div에 특정 클래스의 자식이 있는지 확인 (0) | 2020.08.20 |
Docker 컨테이너가 호스트 컴퓨터와 시간을 자동 동기화합니까? (0) | 2020.08.20 |
jboss 서버 시작 오류 (0) | 2020.08.20 |
MySQL을 사용하여 테이블에 레코드 인덱스를 포함하는 열을 어떻게 생성 할 수 있습니까? (0) | 2020.08.20 |