Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create new entities based on old entities in Entity Framework?

I need to

  1. load some entities into memory,

  2. change a couple of its 'scalar'

  3. property values -without touching its Navigation Properties. and

  4. 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?

like image 786
pencilCake Avatar asked Nov 16 '25 14:11

pencilCake


1 Answers

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();
like image 87
Pop Catalin Avatar answered Nov 18 '25 05:11

Pop Catalin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!