I am using SQL-Server 2016 and Entity Framework Core.
Let's say we want to use a concatenated string to a sequence as a primary key of a table.
I have created the table using Code-First migration successfully, and have set the default value of the column to be the desired concat (Screenshot from SSMS):
When I insert rows to the table manually using the INSERT command, it works as expected. If I choose to omit the value of the column, it is generated from the sequence, otherwise - it uses the value provided.
However, when I try to insert entities by code - an exception is being thrown
System.InvalidOperationException: 'Unable to create or track an entity of type 'EntityName' because it has a null primary or alternate key value.'
The relevant field of the entity is a simple string property. I tried adding [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
annotation, but that didn't help.
EDIT : When I call Add (Sync)
stack trace -
Result StackTrace:
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NullableKeyIdentityMap`1.Add(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode node)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph(EntityEntryGraphNode node, Func`2 handleNode)
at Microsoft.EntityFrameworkCore.DbContext.SetEntityStates(IEnumerable`1 entities, EntityState entityState)
When I call AddAsync
stack trace -
Result StackTrace:
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NullableKeyIdentityMap`1.Add(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode node)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph(EntityEntryGraphNode node, Func`2 handleNode)
at Microsoft.EntityFrameworkCore.DbContext.SetEntityStates(IEnumerable`1 entities, EntityState entityState)
at Microsoft.EntityFrameworkCore.DbContext.AddRangeAsync(IEnumerable`1 entities, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.AddRangeAsync(IEnumerable`1 entities, CancellationToken cancellationToken)
at (Rest of the stack trace...)
Any suggestions? Thanks
You can try to set StoreGeneratedPattern value to Identity. I am using Database First approach and setting this property helped me a lot.