Не могу создать несколько идентификаторов, но у меня есть только один - PullRequest
0 голосов
/ 26 апреля 2018

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

public class CustomerContracts
{
    [Key, Column("ItemId")]  //This change the name of the column when you are using migration.  If you have a form created already, you have to change the connection in the for to aim the new column name.  

    public int ItemId { get; set; }

    public string Description { get; set; }

    public string CustomerRef { get; set; }


    public int ContractTypeId { get; set; }

    public DateTime StartDate { get; set; }

    public DateTime EndDate { get; set; }

    public bool isActive { get; set; }
    [DecimalPrecision(18, 2)]
    public decimal Price { get; set; }

}

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

Укажите флаг '-Verbose' для просмотра операторов SQL, применяемых к целевой базе данных. Применение явных миграций: [201804260855058_firstmigration]. Применение явной миграции: 201804260855058_firstmigration. System.Data.SqlClient.SqlException (0x80131904): несколько столбцов идентификаторов, указанных для таблицы CustomerContracts. Разрешается только один столбец идентификаторов на таблицу. в System.Data.SqlClient.SqlConnection.OnError (исключение SqlException, логическое breakConnection, действие 1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action 1 wrapCloseInAction) в System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning (TdsParserStateObject stateObj, логический callerHasConnectionLock, логический asyncClose) в System.Data.SqlClient.TdsParser.TryRun (RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean) в System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds (String methodName, логический асинхронный, тайм-аут Int32, логический асинхронный) в 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) в System.Data.Entity.Infrastructure.Interception.InternalDispatcher 1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func 3 операция, TInterceptionContext interceptionContext, действие 3 executing, Action 3 выполнено) в System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery (команда DbCommand, DbCommandInterceptionContext interceptionContext) в System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery () в System.Data.Entity.Migrations.DbMigrator.ExecuteSql (MigrationStatementigrationStatement, соединение DbConnection, транзакция DbTransaction, DbInterceptionContext interceptionContext) в System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql (MigrationStatementigrationStatement, соединение DbConnection, транзакция DbTransaction, DbInterceptionContext interceptionContext) в System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal (IEnumerable 1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext) at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable 1igrationStatements, транзакция DbTransaction, DbInterceptionContext interceptionContext) в System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction (IEnumerable 1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext) at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable 1igrationStatements, соединение DbConnection, DbInterceptionContext interceptionContext) в System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal (операция IEnumerable 1 migrationStatements, DbConnection connection) at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass32.<ExecuteStatements>b__30() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func 1) в System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute (Операция действия) в System.Data.Entity.Migrations.DbMigrator.ExecuteStatements (IEnumerable 1 migrationStatements, DbTransaction existingTransaction) at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable 1igrationStatements) в System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements (IEnumerable 1 migrationStatements) at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable 1 операций, 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) в System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade (IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId) в System.Data.Entity.Migrations.DbMigrator.UpdateInternal (String targetMigration) в System.Data.Entity.Migrations.DbMigrator. <> c__DisplayClasse.b__d () в System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists (действие mustSucceedToKeepDatabase) в System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists (действие mustSucceedToKeepDatabase) в System.Data.Entity.Migrations.DbMigrator.Update (String targetMigration) в System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update (String targetMigration) в System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore () в System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run () ClientConnectionId: 8aa18649-614e-4be4-a46d-fb780984d59fНомер ошибки: 2744, состояние: 2, класс: 16 Для таблицы «CustomerContracts» указано несколько столбцов идентификаторов.Допустим только один столбец идентификаторов для каждой таблицы.

Почему я получаю эту ошибку.Как вы можете видеть, я использую только один ключ, и при этом я не переименовываю его (это новая таблица, когда я отбросил БД).Любая помощь приветствуется.

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

 public partial class firstmigration : DbMigration
    {
        public override void Up()
        {
            DropPrimaryKey("dbo.CustomerContracts");
            AddColumn("dbo.CustomerContracts", "ItemId", c => c.Int(nullable: false, identity: true));
            AddPrimaryKey("dbo.CustomerContracts", "ItemId");
            DropColumn("dbo.CustomerContracts", "TeamId");
        }

        public override void Down()
        {
            AddColumn("dbo.CustomerContracts", "TeamId", c => c.Int(nullable: false, identity: true));
            DropPrimaryKey("dbo.CustomerContracts");
            DropColumn("dbo.CustomerContracts", "ItemId");
            AddPrimaryKey("dbo.CustomerContracts", "TeamId");
        }
    }

1 Ответ

0 голосов
/ 26 апреля 2018

Попробуйте это:

public override void Up()
{
    DropPrimaryKey("dbo.CustomerContracts");
    DropColumn("dbo.CustomerContracts", "TeamId"); // Drop this first
    AddColumn("dbo.CustomerContracts", "ItemId", c => c.Int(nullable: false, identity: true));
    AddPrimaryKey("dbo.CustomerContracts", "ItemId");
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...