Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EF trying to Insert into Identity field #6426

Closed
Dethorhyne opened this issue Aug 29, 2016 · 11 comments
Closed

EF trying to Insert into Identity field #6426

Dethorhyne opened this issue Aug 29, 2016 · 11 comments
Labels
closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. type-bug
Milestone

Comments

@Dethorhyne
Copy link

Steps to reproduce

  1. Make a new solution, add NumericId to the ApplicationUser class and make it look like this:
public class ApplicationUser : IdentityUser
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int NumericId { get; set; }
}
  1. Execute UserManager.UpdateAsync(user);
  2. Witness the error

The issue

For some reason EF is attempting to insert value into an Identity column which isn't allowed and throws an exception. Rest of the columns do NOT get updated.

However,
this bug also accured when I tried to register, but in that case, database wise, everything was Inserted, new user was registered and a proper NumericId was assigned to the user even though the front-end threw the exception. Few builds after, even though nothing has changed, registering stopped throwing the exception and functions properly.

Exception message:

SqlException: Cannot update identity column 'NumericId'.
MoveNext

DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
MoveNext

Stack trace:
System.Data.SqlClient.SqlException: Cannot update identity column 'NumericId'.
   at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__107_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.<ExecuteAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.<ExecuteAsync>d__32.MoveNext()
ClientConnectionId:5be684a0-2aee-4a9f-ac8b-9d4bcea49b47
Error Number:8102,State:1,Class:16

Further technical details

EF Core version: 1.0.0
Operating system: Windows 7 Professional
Visual Studio version: VS 2015 Enterprise edition

Other details about my project setup:
None.

@divega divega added this to the 1.1.0 milestone Aug 31, 2016
@rowanmiller rowanmiller modified the milestones: 1.2.0, 1.1.0-preview1 Oct 6, 2016
@AndriySvyryd
Copy link
Member

@Dethorhyne This is a bug in how we handle the data annotation. You can work around this by using Fluent API in OnModelCreating:

modelBuilder
    .Entity<ApplicationUser>()
    .Property(u => u.NumericId)
    .UseSqlServerIdentityColumn();

AndriySvyryd added a commit that referenced this issue Oct 12, 2016
@AndriySvyryd AndriySvyryd modified the milestones: 1.1.0-preview1, 1.2.0 Oct 12, 2016
AndriySvyryd added a commit that referenced this issue Oct 12, 2016
AndriySvyryd added a commit that referenced this issue Oct 13, 2016
AndriySvyryd added a commit that referenced this issue Oct 13, 2016
@AndriySvyryd AndriySvyryd removed their assignment Oct 13, 2016
@AndriySvyryd AndriySvyryd added the closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. label Oct 13, 2016
@brentlyjdavid
Copy link

brentlyjdavid commented Apr 23, 2017

i am still getting this with 1.1.1 and VS 2017. The workaround using the fluent API did not seem to change anything.

image

image

image

web csproj packages:

image

Suggestions? Is it because I'm using a long instead of int?

@ajcvickers
Copy link
Contributor

@brentdavid2008 Can you please open a new issue including a complete code listing or project that reproduces what you are seeing.

@zahik
Copy link

zahik commented May 1, 2017

+1.
Same problem.

@mehdikiani
Copy link

mehdikiani commented Aug 25, 2017

Use Metadata property like this :

Before Entity Frmework core 2.0 :

 builder.Property(p => p.Id)
                .UseSqlServerIdentityColumn();
 builder.Property(p => p.Id)
             .Metadata.IsReadOnlyAfterSave = true;

for Entity framework core 2.0 , The "IsReadOnlyAfterSave" property is deprecated.Use following :

 builder.Property(p => p.Id)
                .UseSqlServerIdentityColumn();
            builder.Property(p => p.Id)
                .Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;

@Gimly
Copy link

Gimly commented Aug 25, 2017

@mkiani3000 I tried to do exactly as you explained on EF Core 2.0 and I'm getting this error message when running Add-Migration:

The property 'Id' on entity type 'Scenario' must be marked as read-only after it has been saved because it is part of a key. Key properties are always read-only once an entity has been saved for the first time.

Here's the code in the OnModelCreating

var scenarioBuilder = modelBuilder.Entity<Person>();

scenarioBuilder.Property(p => p.Id).UseSqlServerIdentityColumn();
scenarioBuilder.Property(p => p.Id).Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;

@ajcvickers
Copy link
Contributor

@Gimly Keys must be marked as PropertySaveBehavior.Throw--key values cannot be changed after the entity has been saved. This is the default, so nothing should need to be set.

@LoopsLu
Copy link

LoopsLu commented Mar 1, 2018

I had this issue too!! I tried to add an annotation [Key, Column(Order = 1)] for my property, but it doesn't work.

Try the method below. I use it to fix my problem (.Net Core and EF Core 1.1.1)

  1. Please add these code in your Context.cs
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);

   // Adding the code below tells DB "NumericId is an AlternateKey and don't update".
   modelBuilder.Entity<User>()
   .HasAlternateKey(x => x.NumericId ).HasName("IX_NumericId");
}
  1. In PackageManager window, execute update-datebase

Ref:
[Stackoverflow] Cannot update identity column 'Index'. EF Core

@Vaishnavi6121995
Copy link

Vaishnavi6121995 commented May 2, 2019

Hello @ajcvickers I m getting this type of error while Inserting a new data to the database, my database is postgresql

{"message":"An error occurred while updating the entries. See the inner exception for details.","detail":" at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)\r\n at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple2 parameters, CancellationToken cancellationToken)\r\n at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func4 operation, Func4 verifySucceeded, CancellationToken cancellationToken) in C:\\projects\\npgsql-entityframeworkcore-postgresql\\src\\EFCore.PG\\Storage\\Internal\\NpgsqlExecutionStrategy.cs:line 49\r\n at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList1 entriesToSave, CancellationToken cancellationToken)\r\n at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)\r\n at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)\r\n at SmartAssistant.LinkMe.Repository.RepositoryBase1.SaveAsync() in D:\\Projects\\ClientProjects\\Recruitment_Agency_Project\\SmartAssistance\\smartassistantsa-smartassistant.whosfit-5aad80240237\\server\\SmartAssistant.LinkMe.Repository\\RepositoryBase.cs:line 48\r\n at SmartAssistant.LinkMe.Repository.EmployerRepository.CreateEmployerAsync(EmployerDBM EmployerDBM) in D:\\Projects\\ClientProjects\\Recruitment_Agency_Project\\SmartAssistance\\smartassistantsa-smartassistant.whosfit-5aad80240237\\server\\SmartAssistant.LinkMe.Repository\\EmployerRepository.cs:line 45\r\n at SmartAssistant.LinkMe.Api.Controllers.EmployerController.CreateEmployee(EmployerDBM Employeer) in D:\\Projects\\ClientProjects\\Recruitment_Agency_Project\\SmartAssistance\\smartassistantsa-smartassistant.whosfit-5aad80240237\\server\\SmartAssistant.LinkMe.Api\\Controllers\\EmployerController.cs:line 69\r\n at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)\r\n at System.Threading.Tasks.ValueTask1.get_Result()\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()\r\n at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)\r\n at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)\r\n at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext context)"}

@ajcvickers
Copy link
Contributor

@Vaishnavi6121995 Please create a new issue and include a small, runnable project/solution or complete code listing that demonstrates the exception you are seeing.

@simeyla
Copy link

simeyla commented Feb 12, 2021

I'm guessing this is now

 scenarioBuilder.Property(p => p.Id).UseIdentityColumn();    // in SqlServerPropertyBuilderExtensions

@ajcvickers ajcvickers modified the milestones: 1.1.0-preview1, 1.1.0 Oct 15, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. type-bug
Projects
None yet
Development

No branches or pull requests