2016-06-25 19 views
1

Mit Entity Framework Code ersten approact auf OFF gesetzt wird, um Daten in eine Tabelle durch den folgenden Befehl ein:Fehler bekommen kann nicht expliziten Wert für Identitätsspalte in der Tabelle ‚Genre‘ einfügen, wenn IDENTITY_INSERT

public partial class PopulateGenresTable : DbMigration 
    { 
     public override void Up() 
     { 
      Sql("INSERT INTO Genres (Id, Name) VALUES (1, 'Melody')"); 
     } 

     public override void Down() 
     { 
     } 
    } 

Das Genre hat der Code wie:

public class Genre 
    { 
     public int Id { get; set; } 

     [Required] 
     [StringLength(255)] 
     public string Name { get; set; } 
    } 

wie folgt definiert: public DbSet<Genre> Genres { get; set; }

Und als ich versuchte, den Befehl update-database immer die follo zu laufen Flügelfehler. Kannst du mir sagen, wo ich falsch liege?

PM> Update-Database 
Value does not fall within the expected range. 
At C:\Projects\GigsHub\packages\EntityFramework.6.1.3\tools\EntityFramework.psm1:977 char:5 
+  $DTE.Solution.SolutionBuild.BuildProject($configuration, $project ... 
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : OperationStopped: (:) [], ArgumentException 
    + FullyQualifiedErrorId : System.ArgumentException 

Value does not fall within the expected range. 
At C:\Projects\GigsHub\packages\EntityFramework.6.1.3\tools\EntityFramework.psm1:977 char:5 
+  $DTE.Solution.SolutionBuild.BuildProject($configuration, $project ... 
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : OperationStopped: (:) [], ArgumentException 
    + FullyQualifiedErrorId : System.ArgumentException 

Specify the '-Verbose' flag to view the SQL statements being applied to the target database. 
Applying explicit migrations: [201606252031479_PopulateGenresTable]. 
Applying explicit migration: 201606252031479_PopulateGenresTable. 
System.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table 'Genres' when IDENTITY_INSERT is set to OFF. 
    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(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:b8a869e0-e2da-4fcb-8ccb-624307ad7b98 
Error Number:544,State:1,Class:16 
Cannot insert explicit value for identity column in table 'Genres' when IDENTITY_INSERT is set to OFF. 
+1

Klingt wie die Tabelle in der Datenbank eingerichtet ist, um den Wert des ID-Attributs beim Einfügen automatisch zu generieren und nicht erlaubt, einen expliziten Wert anzugeben. –

+0

Also, was sind die Schritte, um das zu lösen? Die Tabellendefinition sieht folgendermaßen aus: 'CREATE TABLE [dbo]. [Genres] ( [ID] TINYINT IDENTITY (1, 1) NOT NULL, [Name] NVARCHAR (255) NOT NULL, CONSTRAINT [PK_dbo.Genres] PRIMARY Schlüssel geklammert ([Id] ASC) ); ' – adarksun

+1

IDENTITY ist ein automatisches Inkrement und akzeptiert daher keine expliziten Werte. Entfernen Sie entweder das Schlüsselwort und bauen Sie Ihre Datenbank neu auf oder legen Sie DatabaseGeneratedOption.Identity für diese Spalte fest. – DevilSuichiro

Antwort

0

Nach Mosh Kurs? Ich auch. Ich tat im Grunde Folgendes:

+0

Ich habe gerade diese Antwort von Mosh: https://twitter.com/moshhamedani/status/762623941303230464 Das Problem sollte weggehen, wenn ein Byte anstelle von Int für die Id-Spalte verwendet wird. (ja!) – 8DH

+0

Und was ist mit anderen Entitäten, die sich auf 'Genre' beziehen? Ich denke, es ist nicht der richtige Ansatz, einen bestimmten Datentyp * only * zu verwenden, um zu vermeiden, dass eine Identitätsspalte erzeugt wird. Dafür gibt es Mappings. Wohlgemerkt, jetzt kann es nicht mehr als 255 Genres geben. –