Description
Describe what is not working as expected:
I 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.
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.
The relevant field of the entity is a simple string property. I tried adding [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
(also identity, and none) annotation, but that didn't do the trick. When I set the property to Identity (I called directly the ValueGeneratedOnAdd
through the fluent api) it just generated a GUID, not taking into consideration the default value provided.
If you are seeing an exception, include the full exceptions details (message and stack trace).
Exception message: `System.InvalidOperationException: 'Unable to create or track an entity of type 'EntityName' because it has a null primary or alternate key value.'`
Stack trace: `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)`
I can think of workarounds such as first generating the value manually and only then updating the entity and saving it, or having a column for the sequence generated value, and a trigger update that column, but I'd like to avoid them if possible.
Further technical details
EF Core version: (found in project.json or packages.config) - 1.1.1
Database Provider - Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows
IDE: Visual Studio 2017
(Also opened on StackOverflow)