实体框架“数据库中已经有一个名为'CartProduct'的对象。”

时间:2017-01-31 20:54:39

标签: c# entity-framework

我是第一次在PM控制台add-migration ShopDBMigration写的并收到了文件

    namespace Shop.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class ShopDBMigration : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.CartProduct",
                c => new
                {
                    CartID = c.Int(nullable: false, identity: true),
                    ProductID = c.Int(nullable: false),
                    UserID = c.Int(),
                    Cookie = c.String(maxLength: 50),
                    Count = c.Int(nullable: false),
                    Date = c.DateTime(nullable: false),
                })
                .PrimaryKey(t => t.CartID);

            CreateTable(
                "dbo.Category",
                c => new
                {
                    ID = c.Int(nullable: false, identity: true),
                    CategoryID = c.Int(nullable: false),
                    Link = c.String(nullable: false, maxLength: 50),
                    Name = c.String(nullable: false, maxLength: 50),
                    Description = c.String(nullable: false, maxLength: 500),
                    Keywords = c.String(nullable: false, maxLength: 200),
                    ParentID = c.Int(nullable: false),
                })
                .PrimaryKey(t => t.ID)
                .ForeignKey("dbo.Category", t => t.CategoryID)
                .Index(t => t.CategoryID);

            CreateTable(
                "dbo.Product",
                c => new
                {
                    ProductID = c.Int(nullable: false, identity: true),
                    Name = c.String(nullable: false, maxLength: 200),
                    Description = c.String(nullable: false, maxLength: 400),
                    Description_Title = c.String(nullable: false, maxLength: 200),
                    Product_Description = c.String(nullable: false, maxLength: 2000),
                    Keywords = c.String(nullable: false, maxLength: 200),
                    Title = c.String(nullable: false, maxLength: 200),
                    Link = c.String(nullable: false, maxLength: 150),
                    Count = c.Int(nullable: false),
                    Price = c.Int(nullable: false),
                    BarCode = c.String(nullable: false, maxLength: 50),
                    Image = c.String(nullable: false, maxLength: 200),
                    Date = c.DateTime(nullable: false),
                })
                .PrimaryKey(t => t.ProductID);

            CreateTable(
                "dbo.OrderCustomerInfo",
                c => new
                {
                    ID = c.Int(nullable: false, identity: true),
                    UserID = c.Int(nullable: false),
                    AllName = c.String(nullable: false, maxLength: 100),
                    Phone = c.String(nullable: false, maxLength: 12),
                    Email = c.String(nullable: false, maxLength: 150),
                    City = c.String(nullable: false, maxLength: 100),
                    Region = c.String(nullable: false, maxLength: 100),
                    MailIndex = c.Int(nullable: false),
                    MailType = c.String(nullable: false, maxLength: 50),
                    Processed = c.Int(nullable: false),
                    Additional = c.String(maxLength: 300),
                    Date = c.DateTime(nullable: false),
                })
                .PrimaryKey(t => t.ID)
                .ForeignKey("dbo.User", t => t.UserID, cascadeDelete: true)
                .Index(t => t.UserID);

            CreateTable(
                "dbo.OrderProduct",
                c => new
                {
                    ID = c.Int(nullable: false, identity: true),
                    ProductID = c.Int(nullable: false),
                    ProductLink = c.String(nullable: false, maxLength: 150),
                    ProductName = c.String(nullable: false, maxLength: 200),
                    Count = c.Int(nullable: false),
                    TotalPrice = c.Int(nullable: false),
                    Date = c.DateTime(nullable: false),
                    OrderCustomer_ID = c.Int(),
                })
                .PrimaryKey(t => t.ID)
                .ForeignKey("dbo.OrderCustomerInfo", t => t.OrderCustomer_ID)
                .Index(t => t.OrderCustomer_ID);

            CreateTable(
                "dbo.ProductPhoto",
                c => new
                {
                    ProductID = c.Int(nullable: false),
                    Image = c.String(nullable: false, maxLength: 200),
                    Alt = c.String(nullable: false, maxLength: 50),
                })
                .PrimaryKey(t => new { t.ProductID, t.Image, t.Alt });

            CreateTable(
                "dbo.User",
                c => new
                {
                    UserID = c.Int(nullable: false, identity: true),
                    UserName = c.String(nullable: false, maxLength: 100),
                    FirstName = c.String(nullable: false, maxLength: 100),
                    SecondName = c.String(nullable: false, maxLength: 100),
                    Email = c.String(nullable: false, maxLength: 100),
                    Password = c.String(nullable: false, maxLength: 100),
                    Region = c.String(nullable: false, maxLength: 100),
                    City = c.String(nullable: false, maxLength: 100),
                    EmailToken = c.String(nullable: false, maxLength: 20),
                    AuthenticationToken = c.String(nullable: false, maxLength: 20),
                    Activated = c.Boolean(nullable: false),
                    Date = c.DateTime(nullable: false),
                })
                .PrimaryKey(t => t.UserID);

            CreateTable(
                "dbo.ProductCategories",
                c => new
                {
                    Product_ProductID = c.Int(nullable: false),
                    Category_ID = c.Int(nullable: false),
                })
                .PrimaryKey(t => new { t.Product_ProductID, t.Category_ID })
                .ForeignKey("dbo.Product", t => t.Product_ProductID, cascadeDelete: true)
                .ForeignKey("dbo.Category", t => t.Category_ID, cascadeDelete: true)
                .Index(t => t.Product_ProductID)
                .Index(t => t.Category_ID);

        }

        public override void Down()
        {
            DropForeignKey("dbo.OrderCustomerInfo", "UserID", "dbo.User");
            DropForeignKey("dbo.OrderProduct", "OrderCustomer_ID", "dbo.OrderCustomerInfo");
            DropForeignKey("dbo.ProductCategories", "Category_ID", "dbo.Category");
            DropForeignKey("dbo.ProductCategories", "Product_ProductID", "dbo.Product");
            DropForeignKey("dbo.Category", "CategoryID", "dbo.Category");
            DropIndex("dbo.ProductCategories", new[] { "Category_ID" });
            DropIndex("dbo.ProductCategories", new[] { "Product_ProductID" });
            DropIndex("dbo.OrderProduct", new[] { "OrderCustomer_ID" });
            DropIndex("dbo.OrderCustomerInfo", new[] { "UserID" });
            DropIndex("dbo.Category", new[] { "CategoryID" });
            DropTable("dbo.ProductCategories");
            DropTable("dbo.User");
            DropTable("dbo.ProductPhoto");
            DropTable("dbo.OrderProduct");
            DropTable("dbo.OrderCustomerInfo");
            DropTable("dbo.Product");
            DropTable("dbo.Category");
            DropTable("dbo.CartProduct");
        }
    }
    }

然后我写了update-database -verbose并收到此错误:

Using StartUp project 'Shop'. 
Using NuGet project 'Shop'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
    Target database is: 'DB_A12B9A_ShopDB' (DataSource: .\LOCALSQL, Provider: System.Data.SqlClient, Origin: Configuration).
Applying explicit migrations: [201701312018367_ShopDBMigration].
Applying explicit migration: 201701312018367_ShopDBMigration.
CREATE TABLE [dbo].[CartProduct] (
    [CartID] [int] NOT NULL IDENTITY,
    [ProductID] [int] NOT NULL,
    [UserID] [int],
    [Cookie] [nvarchar](50),
    [Count] [int] NOT NULL,
    [Date] [datetime] NOT NULL,
    CONSTRAINT [PK_dbo.CartProduct] PRIMARY KEY ([CartID])
)
System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'CartProduct' 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& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
   at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable`1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass30.<ExecuteStatements>b__2e()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
   at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
   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:d3c646ad-8f1f-49b1-aef8-b41d89fc1b3c
Error Number:2714,State:6,Class:16
    There is already an object named 'CartProduct' in the database.

我还尝试了空白迁移输入命令add-migration ShopDBMigration -IgnoreChanges然后update-database,然后我更改了ShopDBMigration类并传递了命令add-migration ShopDBMigration,它创建了空白文件ShopDBMigration1,忽略了我所做的更改

1 个答案:

答案 0 :(得分:0)

我做不到。所以我刚创建了新的数据库,并在设置与实体框架的关系时将数据从一个复制到第二个。