Skip to content

Cannot insert entity into DB using attach and EntityState.Added #8264

Closed
@d0pare

Description

@d0pare

I am getting following exception when trying to insert entity by attaching and changing its state.

Microsoft.EntityFrameworkCore.DbUpdateException occurred
  HResult=0x80131500
  Message=An error occurred while updating the entries. See the inner exception for details.
  Source=Microsoft.EntityFrameworkCore.Relational
  StackTrace:
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple`2 parameters)
   at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](Func`2 operation, Func`2 verifySucceeded, TState state)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at EFCoreTest.Program.Main() in C:\Users\Dopare\documents\visual studio 2017\Projects\EFCoreTest\EFCoreTest\Program.cs:line 22

Inner Exception 1:
SqlException: Cannot insert explicit value for identity column in table 'Persons' when IDENTITY_INSERT is set to OFF.

Steps to reproduce

Sample repo

using (var db = new AppDbContext())
{
    var person = new Person
    {
        FirstName = "FirstName",
        LastName = "LastName",
        BirthDate = DateTime.Now
    };

    db.Persons.Attach(person);
    db.Entry(person).State = EntityState.Added;

    db.SaveChanges();
}

Further technical details

EF Core version: 1.1.1
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10 x64
IDE: (e.g. Visual Studio 2015)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions