There is already an object named in the database как исправить

Update-Database failed from Package Manager Console.
I’ve used Entity Framework 6.x and code-first approach.
Error is

«There is already an object named ‘AboutUs’ in the database.»

How can I solve this problem?

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)
    {

    }
}

My DbContext is:

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; }
}

Package Manage Console:

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> 

In this guide, we will walk you through the process of troubleshooting the «There is already an object named in the database» error in SQL Server. This error typically occurs when you try to create a table, view, or other database objects with a name that already exists in the database. We will also cover some frequently asked questions related to this error.

Table of Contents

  • Step 1: Identify the Duplicate Object
  • Step 2: Rename or Drop the Duplicate Object
  • Step 3: Verify Object Names in Scripts and Stored Procedures
  • Step 4: Create the New Object
  • FAQs

Step 1: Identify the Duplicate Object

The first step in troubleshooting this error is to identify the duplicate object causing the issue. You can use the following query to search for the object in your database:

USE YourDatabaseName;
GO
SELECT * FROM sys.objects
WHERE name = 'YourObjectName';

Replace YourDatabaseName with the name of your database, and YourObjectName with the name of the object you are trying to create.

Here is the official Microsoft documentation on the sys.objects catalog view for more information.

Step 2: Rename or Drop the Duplicate Object

Once you have identified the duplicate object, you can either rename or drop it, depending on your requirements.

Rename the Object

To rename the object, use the sp_rename stored procedure. For example, to rename a table:

USE YourDatabaseName;
GO
EXEC sp_rename 'YourObjectName', 'NewObjectName';

Replace YourDatabaseName, YourObjectName, and NewObjectName with the appropriate values for your situation.

Here is the official Microsoft documentation on the sp_rename stored procedure for more information.

Drop the Object

To drop the object, use the DROP statement. For example, to drop a table:

USE YourDatabaseName;
GO
DROP TABLE YourObjectName;

Replace YourDatabaseName and YourObjectName with the appropriate values for your situation.

Here is the official Microsoft documentation on the DROP TABLE statement for more information.

Step 3: Verify Object Names in Scripts and Stored Procedures

Before creating the new object, it’s essential to verify the object names in your scripts and stored procedures to avoid future conflicts. Make sure you update any references to the old object name with the new object name.

Step 4: Create the New Object

After resolving the duplicate object issue, you can now create the new object with the desired name. Make sure to verify your script or stored procedure for any errors before running it.

FAQs

1. What are the common causes of the «There is already an object named in the database» error?

The most common cause of this error is trying to create a new object with a name that already exists in the database. It can also occur if you are restoring a database backup and the object names conflict with existing objects.

2. What types of objects can cause this error?

The error can occur with any database object, such as tables, views, stored procedures, functions, and triggers.

3. Can I have objects with the same name in different schemas?

Yes, you can have objects with the same name in different schemas. In this case, you need to use the schema name as a prefix when referencing the object.

4. How can I prevent this error from occurring in the future?

To prevent this error, make sure to check for existing objects with the same name before creating new objects. You can also use a naming convention for your objects to reduce the chances of conflicts.

5. How do I find all objects with a specific name in my database?

You can use the sys.objects catalog view to search for objects with a specific name. Refer to the query in Step 1 for an example.

Back to Top

Написал первый скрипт для MS SQL Server.
Первый раз запустил — отработал нормально.
Теперь вылезает ошибка «There is already an object named … in the database».

Скрипт:

-- начинаем работать в контексте системной базы данных [master]
USE [master]
GO

-- если база данных [dbRBL] уже существует, уничтожаем ее
IF EXISTS (SELECT name FROM sys.databases WHERE name = N'dbRBL')
DROP DATABASE [dbRBL]
GO

-- создаём базу данных [dbRBL]
CREATE DATABASE [dbRBL]
GO

-- переходим в контекст созданной базы данных [dbRBL]
USE [dbSPJ]
GO

-- создаём таблицу читателей [R]
CREATE TABLE [dbo].[R] (
[Rno] [int] IDENTITY(1,1) NOT NULL,
[Rname] [varchar](100) NOT NULL,
[Rsex] [varchar](10) NULL,
[Rbirthday] [date] NULL,
[Rphone] [varchar](30) NULL
)
GO

-- создаём таблицу книг [B]
CREATE TABLE [dbo].[B] (
[Bno] [int] IDENTITY(1,1) NOT NULL,
[Bname] [varchar](100) NOT NULL,
[Bauthor] [varchar](100) NULL,
[Byear] [date] NULL,
[Bpages] [int] NULL,
[Bweight] [int] NULL,
[Bcopies] [int] NULL
)
GO

-- создаём таблицу библиотек [L]
CREATE TABLE [dbo].[L](
[Lno] [int] IDENTITY(1,1) NOT NULL,
[Ladress] [varchar](150) NOT NULL,
[Ldate] [date] NULL,
[Lquantity] [int] NULL,
[Lphone] [varchar](30) NULL
)
GO

-- создаём таблицу записей
CREATE TABLE [dbo].[RBL](
[Rno] [int] NOT NULL,
[Bno] [int] NOT NULL,
[Lno] [int] NOT NULL,
[RBLdate] [date] NULL
)
GO

The there is already an object named in the database fixes error occurs because of already having the same object in the database. If you have changed the namespace or your table is empty, you can also face this error.there is already an object named in the database

You can solve this issue by renaming the new object, updating a database using EF, updating the namespace, etc. Keep reading this article to find all the causes, solutions, and expert recommendations.

Contents

  • Why Am I Getting There Is Already an Object Named in the Database Error?
    • – The Object Already Exists in the Same Database
    • – You Have Changed the Namespace in Your Project
    • – Empty Table
    • – Migration Process Issue
  • How To Fix the There Is Already an Object Named in the Database Issue?
    • – Rename the New Object
    • – Update a Database Using Entity Framework
    • – Create a Migration
    • – Update the Namespace
    • – Hardcode the Context Value
    • – Set AutomaticMigrationsEnabled to False
    • – Add Rows to the EFMigrationsHistory Table
    • – Correct Connection String
  • FAQs
    • 1. Why You Face There Is Already an Object Named in the Database Error?
  • Conclusion

Why Am I Getting There Is Already an Object Named in the Database Error?

You are getting there is already an object named in the database because of having the same object in the database, change in the namespace in your project, empty table, or any issue in the migration process, manual modification of the database, running the update-database command multiple times, etc.

Let’s see the leading causes behind the error so that we can find their solutions in the next section.

– The Object Already Exists in the Same Database

One of the leading causes of already an object named in the database is that the database object you are trying to create is already there in the same database, mainly if you are using an SQL server.

You might have accidentally run the same create statement multiple times. This can happen if you are working with multiple scripts or SQL statements that create objects with the same name, and you might be unaware of this because you are not keeping track of the objects you have created.

This can also occur when the AutomaticMigrationsEnabled setting is set to true, resulting in unpredictable migrations and a lack of control over the database structure.

– You Have Changed the Namespace in Your Project

If you have made changes to the namespace of your project, you can face this error. Suppose your database name is myDatabase.__MigrationHistory, which has a column named NamespaceKey.There Is Already an Object Named in the Database Causes

There the column holds the namespace of your project, and if you change the namespace in your code and if you have not updated the namespace in the NamespaceKey column of the myDatabase.__MigrationHistory table, this error will appear.

– Empty Table

You can encounter this issue if your EFMigrationsHistory table is empty. So when you try to run the update-database, this would have caused the initial migration to be rerun and tables to be recreated, and that’s how the error would have appeared.

The EFMigrationsHistory could be emptied due to an issue with the database or a mistake made while working with the database. Before going for fixing this issue, you must determine the cause of the empty table and take steps to restore the data or modify your database to account for the missing information.

– Migration Process Issue

The cause of this error could be the issue in the migration process; there, you might see the error there is already an object named ” in the database migration. This error occurs when you try to run a database migration in a system that uses an entity framework.

That framework attempts to create a new database object that could be a table, view, or stored procedure and counters an existing object.

This error is similar to the main error discussed in this article.

You can fix the there is already an object named in the database by renaming the new object, updating a database using EF, creating a migration, updating the namespace, Hardcoding the context value, or setting AutomaticMigrationsEnables to false.



There could be a couple of more solutions depending on your case.

– Rename the New Object

If you are getting this error because of having the same object in the same database, you must either rename the new object to a unique name or drop the existing object and recreate it with the desired name.

You can use the DROP statement to delete the existing object and rerun the new object’s creation statement. Make sure to use a unique name for the new object to avoid future conflicts.

– Update a Database Using Entity Framework

To eliminate an object named ” in the database migration or there is already an object named in the database entity framework, you need to update a database using Entity Framework.There Is Already an Object Named in the Database Solutions

For that, you can follow the below steps.

First, you need to add a new migration; you can use the Add-Migration command and then add a name for the migration and the -IgnoreChanges flag. This will create a new migration file that contains the changes you want to make to the database.

After making the necessary changes to the database, you can use the Update-Database command and the -verbose flag to apply the changes from the Initial migration file to the database. The -verbose flag will display additional information about the update process in the console.

You can run these commands from the Package Manager Console, a command-line interface for managing NuGet packages and interacting with Entity Framework.

– Create a Migration

If there is no -IgnoreChanges currently in Entity Framework Core, you can have that by commenting out the code in the up() of the migration file. This will take a snapshot of the current model state, which means that subsequent migrations will only include changes made after the snapshot was taken.

Suppose you have already made some incremental model changes and want to create a baseline migration. In that case, you will need to remove these changes, apply the baseline migration, and then add your changes and create a second migration.

This will allow you to track the changes to your model in a structured way and apply them to the database.

– Update the Namespace

We will suppose the same database name as myDatabase.__MigrationHistory and the column name as NamespaceKey. If you have changed the namespace in your code, It is essential to update the namespace in the NamespaceKey column of the myDatabase._MigrationHistory table.

This confirms that the namespaces in your code and database are consistent, as failing to update the namespace in the database can result as there is already an object named ‘pk_’ in the database error with different namespaces.

For example, if you change the namespace to EFDataAccess in your code, you should update the values of the NamespaceKey column in the myDatabase.__MigrationHistory table to EFDataAccess.Migrations.Configuration.

And then, you can run the update-database command from the Package Manager Console to apply these changes.

– Hardcode the Context Value

You can also use a different approach where you can hardcode the context value in your code to the old namespace value by following these steps:There Is Already an Object Named in the Database More Solutions

  1. Create a class called YourDbMigrationConfiguration that inherits from DbMigrationsConfiguration<YourDbContext>.
  2. In the constructor of this class, assign the old context value to the NamespaceKey property.
  3. Create another class called YourDbInitializer that inherits from MigrateDatabaseToLatestVersion<YourDbContext, YourDbMigrationConfiguration>.
  4. Leave this class empty.
  5. In the static constructor of your DbContext class, call Database.SetInitializer(new YourDbInitializer()).

– Set AutomaticMigrationsEnabled to False

It is recommended to set AutomaticMigrationsEnabled to false and employ coded migrations as an alternative. Doing so will avoid problems with duplicate objects and ensure that each developer on the team uses the same database.

Alternatively, you can combine automatic and scripted migrations if you’re the only developer working on the project and are diligent with your updates. However, it is essential to be careful and not add duplicate objects to the database.

– Add Rows to the EFMigrationsHistory Table

To fix the issue, you can add rows to the EFMigrationsHistory table. Each row represents a migration applied to the database and will include two columns that are MigrationID and ProductVersion.

The MigrationId column contains the name of the migration file, while the ProductVersion column contains the version of EF used to apply the migration.

– Correct Connection String

Ensure that the project you want to run as the main project has the correct connection string in its configuration file. Alternatively, when running the update-database command, you can specify the main project using the StartUpProjectName parameter.

This parameter tells the program which configuration file to use for named connection strings. If you don’t include this parameter, the program will use the configuration file of the specified project.

FAQs

1. Why You Face There Is Already an Object Named in the Database Error?

You can face there is already an object named in the database error while working with any programming language, framework, or IDE that supports database integration. You might see a variation in that error depending on where you are seeing this error.

For example, you can face the below error if you work with visual studio, stored procedures in DBMS like Microsoft SQL server or Oracle, C# programming error, and Django web framework, respectively.

  • There is already an object named in the database visual studio.
  • There is already an object named in the database stored procedure.
  • There is already an object named in the database c#.
  • There is already an object named in the database django.

Conclusion

There is already an object named in the database is a common error to occur; however, you now know how to deal with it while avoiding other errors. Let’s see what we learned today:

  • You can see this error message if you try to create an object with a name already in use in the database.
  • Changing the namespace in your project can also lead you to face this error.
  • Renaming the new object or updating the database using EF are two go-to solutions.

We explored some significant issues and their solutions. Now you should be able to find your solutions, and if you ever get confused, you can always get help from this article.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Ошибка обновления базы данных из консоли диспетчера пакетов.
Я использовал 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> 

4b9b3361

Ответ 1

Кажется, есть проблема в процессе миграции, запустите команду add -igration в «Консоли диспетчера пакетов»:

Начальная версия надстройки -IgnoreChanges

выполните некоторые изменения, а затем обновите базу данных из файла «Initial»:

Обновление базы данных -verbose

Изменить: -IgnoreChanges находится в EF6, но не в EF Core, вот обходной путь: fooobar.com/questions/13639947/…

Ответ 2

Возможно, вы изменили пространство имен в своем проекте!
В вашей базе данных есть таблица dbo.__MigrationHistory. В таблице есть столбец с именем ContextKey.
Значение этого столбца основано на вашем namespace. например, это «DataAccess.Migrations.Configuration«.
Когда вы меняете пространство имен, оно вызывает дубликаты имен таблиц с разными пространствами имен.
Итак, после того, как вы измените пространство имен на стороне кода, также измените пространство имен в этой таблице в базе данных (для всех строк).
Например, если вы измените пространство имен на EFDataAccess, то вы должны изменить значения столбца ContextKey в dbo.__MigrationHistory на «EFDataAccess.Migrations.Configuration«.
Затем со стороны кода в Tools = > Package Manager Console используйте команду update-database.

Другим вариантом вместо изменения значения контекста в базе данных является жесткое кодирование значения контекста в вашем коде для старого значения пространства имен. Это возможно, наследуя DbMigrationsConfiguration<YourDbContext>, и в конструкторе просто присвойте старое значение контекста ContextKey, чем наследуйте от MigrateDatabaseToLatestVersion<YourDbContext, YourDbMigrationConfiguration> и оставьте этот класс пустым. Последнее, что нужно сделать, это вызвать Database.SetInitializer(new YourDbInitializer()); в вашем DbContext в статическом конструкторе.

Я надеюсь, что ваша проблема будет исправлена.

Ответ 3

«В базе данных уже есть объект с именем» AboutUs «.

Это исключение говорит вам, что кто-то добавил базу данных уже «AboutUs» в базу данных.

AutomaticMigrationsEnabled = true; может привести к этому, так как версии базы данных в этом случае не контролируются вами. Чтобы избежать непредсказуемых миграций и убедиться, что каждый разработчик в команде работает с той же структурой базы данных , я предлагаю установить AutomaticMigrationsEnabled = false;.

Автоматические миграции и закодированные миграции могут жить вместе, если вы очень осторожны и единственный разработчик в проекте.

В Центре разработчиков данных есть цитата из сообщения «Автоматический ввод кода первой миграции» :

Автоматическая миграция позволяет использовать первые миграции кода без имея файл кода в вашем проекте для каждого внесенного вами изменения. Не все изменения могут применяться автоматически — например, переименования столбцов требуют использования миграции на основе кода.

Рекомендация для командной среды

Вы можете пересекать автоматические и кодовые миграции, но это не рекомендуется в сценариях разработки команд. Если вы являетесь частью команда разработчиков, использующая систему управления версиями, вы должны либо использовать чисто автоматические миграции или чисто кодовые миграции. Учитывая ограничения автоматических миграций мы рекомендуем использовать на основе кода миграции в командной среде.

Ответ 4

В моем случае моя таблица EFMigrationsHistory была опустошена (как-то), и при попытке запустить update-database я бы получил:

В базе данных уже есть объект с именем «AspNetUsers»

После того, как таблица была опустошена, имело смысл, что она пыталась перезапустить начальную миграцию и пыталась воссоздать таблицы.

Чтобы устранить эту проблему, я добавил строки в таблицу EFMigrationsHistory. 1 строка для каждой миграции, о которой я знал, что база данных обновлена.

Строка будет содержать 2 столбца: MigrationId и ProductVersion

MigrationId — это имя файла миграции. Пример: 20170628112345_Initial

ProductVersion — это версия ef, которую вы запускаете. Вы можете найти это, введя Get-Package в Консоль диспетчера пакетов и ищите свой пакет ef.

Надеюсь, это поможет кому-то.

Ответ 5

В моем случае я переименовал сборку, содержащую модель фреймворка сущности кода. Хотя фактическая схема не изменилась во всех таблицах миграций, называемых

dbo.__MigrationHistory

содержит список уже выполненных миграций на основе старого имени сборки. Я обновил старое имя в таблице миграции, чтобы он соответствовал новому, и затем миграция снова работала.

Ответ 6

Убедитесь, что ваш проект запуска решений имеет правильную строку подключения в файле конфигурации. Или установите параметр -StartUpProjectName при выполнении команды update-database. Параметр -StartUpProjectName указывает файл конфигурации, который будет использоваться для именованных строк подключения. Если опущен, используется указанный файл конфигурации проектов.

Вот ссылка для ссылок на команды ef -igration http://coding.abel.nu/2012/03/ef-migrations-command-reference/

Ответ 7

Примечание. Не рекомендуется решение. но быстро исправить в некоторых случаях.

Для меня dbo._MigrationHistory в производственной базе данных пропущены записи миграции во время процесса публикации, но база данных разработки имела все записи миграции.

Если вы уверены, что у производственной базы данных есть аналогичная и новейшая схема по сравнению с dev db, скопируйте все записи миграции в производственный db, чтобы решить проблему.

Вы можете делать только в VisualStudio.

  • Откройте панель «Проводник SQL Server» > щелкните правой кнопкой мыши таблицу dbo._MigrationHistory в базе данных источника (в моем случае dev db) > Нажмите «Сравнение данных…».
  • Затем запустится мастер сопоставления данных, выберите целевую базу данных (в моем случае для производства db) и нажмите «Далее».
  • Через несколько секунд он покажет некоторые записи только в исходной базе данных. просто нажмите кнопку «Обновить цель».
  • В браузере нажмите кнопку обновления и посмотрите сообщение об ошибке.

Обратите внимание, что, опять же, это не рекомендуется в сложном и серьезном проекте. Используйте это только у вас есть проблема во время обучения ASP.Net или EntityFramework.

Ответ 8

У меня была такая же проблема, и после трех часов борьбы я выясняю, что происходит

В моем случае, когда я впервые захотел выполнить миграцию в методе up(), код по умолчанию хочет создать уже существующие таблицы, поэтому я получил ту же ошибку, что и вы

Чтобы решить эту проблему, просто удалите этот код и напишите, что хотите. Например, я хотел добавить столбец, поэтому я просто пишу

migrationBuilder.AddColumn<string>(
            name: "fieldName",
            table: "tableName",
            nullable: true);

Ответ 9

Удалите строки из таблицы dbo_MigrationHistory или удалите таблицу и запустите

update-database -verbose

Он будет запускать все миграции в проекте по одному

Ответ 10

В моём случае проблема была в сеидере. Я вызывал _ctx.Database.EnsureCreated() внутри него, и, насколько я понял, команда обновления базы данных успешно выполнена, но затем Сеидер попытался создать базу данных «второй раз».

Как обратиться:

  1. Запустите обновление, просто запустите приложение и вызовите EnsureCreated(). База данных будет создана/обновлена
  2. Закомментируйте или удалите сеялку.

Ответ 11

Очередной сценарий EF Core.

Убедитесь, что у вас есть файл Migrations/YOURNAMEContextModelSnapshot.cs.

как подробно описано в — https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#create-a-migration

Если вы попытались заново создать базу данных вручную, удалив файлыigration.cs, будьте осторожны, так как ваш файл Migrations/* ContextModelSnapshot.cs все еще существует.

Без этого у ваших последующих миграций не будет снимка, на котором можно создать необходимые различия, а ваши новые файлы миграции будут выглядеть так, как будто они воссоздают все заново, с нуля, тогда вы получите ошибку существующей таблицы, как описано выше.

Ответ 12

Просто выполните команду update -igration -Script. Это генерирует новый *.sql скрипт, который включает все изменения БД, включенные в миграцию. В конце кода команды вставки выглядят примерно так: INSERT [dbo]. [__ MigrationHistory] ([MigrationId], [ContextKey], [Model], [ProductVersion]), вы можете просто запустить все эти INSERT, и БД будет синхронизирована

Ответ 13

После более часа отсутствия результатов я попробовал другой подход, не используя миграции, но я сравнил схему.

В Visual Studio → Инструменты → SQL Server → Сравнение новой схемы

Сначала я создал новую совершенно новую базу данных с EF-миграциями. Затем я сравнил новую базу данных с той, которую хотел обновить. Наконец сгенерировал скрипт миграции, и я смог выполнить обновление схемы.

Ответ 14

В моем случае (хочу сбросить и получить новую базу данных),

Сначала я получил сообщение об ошибке: There is already an object named 'TABLENAME' in the database.

и я увидел немного раньше:

"Applying migration '20111111111111_InitialCreate'.
Failed executing DbCommand (16ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE MYFIRSTTABLENAME"

Моя база данных была создана, но в истории миграции нет записей.

Я отбрасываю все таблицы, кроме dbo.__ MigrationsHistory

Миграции История была пуста.

Запустите dotnet ef database update -c StudyContext --verbose

(—verbose просто для удовольствия)

и получил Done.

Ответ 15

Я столкнулся с той же ошибкой, что и ниже. Затем я исправил это, как показано ниже:

  1. Проверьте текущие базы данных в вашем проекте:
    • dotnet ef migrations list
  2. Если вы добавили самое новое, удалите его:
    • dotnet ef migrations remove
  3. Гарантированные выходные данные этой базы данных должны быть обнаружены в исходном коде: файлы .cs/.Designer.cs

4. Теперь все в порядке. Попробуйте еще раз добавить:
 dotnet ef migrations add [new_dbo_name]

5. Наконец, попробуйте обновить еще раз, в базе данных о списке миграции:

  • dotnet ef database update [First]
  • dotnet ef database update [Second]
  • dotnet ef database update [new_dbo_name]

Надеюсь, это полезно для вас. ^^

Ответ 16

то же самое случилось со мной..
Проблема заключалась в том, что на самом деле я удалил свою таблицу базы данных MoviesCast и создал новую таблицу, и проблема заключалась в том, что моя последняя миграция пыталась вызвать удаленную таблицу MoviesCast в базе данных.
Я решил это, просто удалив все содержимое последней миграции, и просто запустил Up() & метод down()

public override void Up()
{
}

public override void Down()
{
}

затем обновите базу данных и просто добавьте новую миграцию

Ответ 17

Вы удалили папку миграции, чем пытаетесь запустить команду «update-database» на консоли диспетчера пакетов? если так

Просто вручную удалите все ваши таблицы
Чем запустить, если update-databse (данные семени минусов будут удалены)

Ответ 18

В файле миграции проверьте метод public override void Up(). Возможно, вы пытаетесь создать новый объект db, который уже находится в базе данных.
Итак, перед созданием объекта db вам нужно отбросить этот объект/таблицу. Просто сделай, как рев —

DropTable("dbo.ABC"); 
CreateTable(
            "dbo.ABC",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    ..
                 }

И теперь запустите миграцию     Update-Database -TargetMigration: "2016_YourMigration"

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как составить набор данных
  • Как найти кота приметы
  • Как найти попутчика для мотопутешествия
  • Как исправить пенал
  • Как найти яндекс каналы на телевизоре

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии