在数据库中已经存在一个被命名的对象。

144

从程序包管理器控制台更新数据库失败。

我使用了Entity Framework 6.x和Code First方法。

错误信息为"There is already an object named 'AboutUs' in the database."

我该如何解决这个问题?

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> 

我该怎么做(映射到现有设计)? - x19
15
如果“精心设计的数据库”可以使用EF映射到对象模型中,那么EF也可以生成它。数据库迁移是一种强大的工具,可以使您的数据库部署更加容易。我不建议避免使用数据库迁移。否则,补丁脚本仍然是必需的。我建议正确使用数据库迁移。 - Ilya Palkin
31个回答

2

同样的情况(服务器上没有数据库和MigrationHistory表)。我的步骤如下:

  1. 我从第一个迁移的Up和Down部分删除了迁移数据。
  2. 使用空迁移更新数据库(创建了MigrationHistory表)
  3. 添加你的真正的迁移并更新数据库。

1

另一个 EF Core 场景的边缘情况。

请检查您是否有 Migrations/YOURNAMEContextModelSnapshot.cs 文件。

详见 - https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/#create-a-migration

如果您尝试通过删除 migration.cs 文件手动重新创建数据库,请注意确保 Migrations/*ContextModelSnapshot.cs 文件仍然存在。

没有它,您的后续迁移将没有快照可用于创建所需差异,您的新迁移文件看起来会像是要从头开始重新创建所有内容,然后您将出现上述的现有表格错误。


1

你删除了迁移文件夹,然后尝试在包管理器控制台上运行“update-database”命令吗?如果是这样的话

只需手动删除所有表格 然后运行if update-databse(cons种子数据将被删除)


1

我遇到了Elnaz提到的相同问题。在我们项目重构期间,我需要更改datalayer的命名空间。这导致迁移无法看到数据库中的现有迁移。我发现James Chambers博客上有一个很好的解决方案。

http://jameschambers.com/2014/02/changing-the-namespace-with-entity-framework-6-0-code-first-databases/

我只是在迁移配置文件中做了以下更改。
public Configuration()
{
    AutomaticMigrationsEnabled = false;
    this.ContextKey = “Old_Namespace.Migrations.Configuration”;
}

希望这可以帮助其他有困难的人。

在命名空间更改后,我遇到了类似的情况。尝试了这个修复方法,但仍然没有起作用。所以我手动修改了数据库表中的命名空间,然后它开始工作了。 - kosist

1
同样的问题也发生在我身上。问题是我删除了数据库表MoviesCast,并创建了一个新表,但我的最后一次迁移尝试在数据库中引入已删除的表MoviesCast。我通过简单地删除最后一次迁移的所有内容,然后运行Up()和down()方法来解决它。
public override void Up()
{
}

public override void Down()
{
}

然后更新数据库并简单地添加新迁移。

0

我的问题可能有点特殊,但是我也遇到了这个错误。问题出在我的AppDbContext.cs文件中有一个OnConfiguring()方法,它指向了另一个已经存在该对象的数据库。使用-verbose参数帮助我找到了这个问题。

我删除了OnConfiguring方法,但是我的Update-Database命令抛出了不同的错误。最终我意识到必须在我的AppDbContext.cs文件中保留OnConfiguring方法,并包含实际的数据库连接字符串。当然,这是多余的,我知道在代码中包含用户/密码信息并不安全,但是一旦我做出了这些更改,我的Update-Database命令就可以正常工作了,没有任何错误。下面是相关的代码。如果有人有更好的解决方法,请随时提出建议。

// my appdbcontext.css file 
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseSqlServer("Server=myserver;Database=mydatabase;MultipleActiveResultSets=true;User ID=myuser;Password=mypass");                
    }
}

// my program.cs
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));  

0
在我的情况下(想要重置并获取一个新的数据库),首先我收到了错误信息: 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之外的所有表格。

MigrationsHistory是空的。

运行 dotnet ef database update -c StudyContext --verbose

(--verbose只是为了好玩)

然后得到了 Done.


0

另一种做法是在初始类、上下方法之间注释所有内容,然后运行 update-database,成功运行种子方法后再次运行 update-database。这可能对一些朋友有所帮助。


0

注意:我这样做是因为我的数据库里没有任何内容。 在我的情况下: 1. 我通过包管理器控制台的命令remove-migration移除了一个迁移 2. 通过'SQL Server对象资源管理器'面板,选择当前数据库,右键点击,选择删除来移除数据库 3. 在包管理器控制台中输入Add-Migration并按Enter键进行迁移 4. 最后使用命令update-database进行更新


0
我也遇到了同样的问题。我尝试了以下解决方案: 1. 删除Up()方法中的创建表代码以及Down()方法中相关的代码。 2. 在Package Manager Console中运行update-database命令。
这个方法解决了我的问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接