Closed popcatalin81 closed 2 years ago
@popcatalin81 You can tell EF that values are temporary, but we don't have any nice top-level API for this yet, so you have to drop down to our lower-level "internal" APIs:
using (var db = new TreeContext())
{
db.Node.AddRange(nodes);
var idProperty = db.Model.FindEntityType(typeof(Node)).FindProperty("Id");
foreach (var node in nodes)
{
db.Entry(node).GetInfrastructure().MarkAsTemporary(idProperty);
}
//Assert Fixup works
Debug.Assert(nodes[4].Parent != null && nodes[4].Parent.Id == -3);
db.SaveChanges();
}
Keep in mind that these internal APIs may change between releases, so use only at your own risk. We will add top-level public API to do this in a future release.
Thanks @ajcvickers, this is great until the feature is surfaced.
Consider the following scenario:
A graph of entities is sent over the wire in serialized form without relationships, just scalar and foreign key properties (Typical case for serializes that do not support cyclic references: IE: Microsoft Bond) in order to be inserted.
The graph is attached to the context in the Added state. Then Entity Framework performs the Relationship FixUp.
The issue
Expected: Entity Framework to insert the graph obeying the Identity specification. Actual: Exception: Cannot insert explicit value for identity column in table 'Node' when IDENTITY_INSERT is set to OFF
Repro application:
The workaround to detach the graph, set the id to 0 is quite ugly for this scenario.
The better approach would be for the API to be explicit whether a to perform the insert using the temporary key or not.
Further technical details
EF Core version: 1.0.0-rc2-final Operating system: Windows 10 Visual Studio version: VS 2015
Other details about my project setup: