I need to
load some entities into memory,
change a couple of its 'scalar'
property values -without touching its Navigation Properties. and
SAVE them as a NEW Entity into the Db.
How can I achieve this in EntityFramework, is it enough to set the object's ID to NULL to save it as a new entity or what should be the trick?
You simply need to change the entity state from Modified to Added and Entity Framework will perform an insert instead of an update.
Example using DbContext API:
DbContext context = // ...
foreach (var entityEntry in context.ChangeTracker.Entries())
{
if (entityEntry.State == EntityState.Modified)
entityEntry.State = EntityState.Added;
}
ct.SaveChanges();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With