0

So i want to update an entry's Valid to column, and then insert a new copy of it with a new value. The issue is it seems to skip the update statement, and just inserts a new copy of it.

foreach (Model data in Data)
{
   var entry = context.table.Where(x=>x.id == data.id).FirstOrDefault();
   entry.ValidTo = DateTime.Now;
   ctx.Update(entry);
   entry.id = 0;
   entry.ValidTo = new DateTime(9999, 12, 31);
   entry.ValidFrom = DateTime.Now;
   entry.Value = adjustmentmodel.Value;
   ctx.Add(entry);
}
ctx.SaveChanges();

I tried inserting a saveChanges after ctx.update(entry), and that works, but is pretty slow. So i wanted to hear if there was a way, to only have to save the changes at the end?

I am using dotnet 5 and EF core 5.0.17

Nick
  • 43
  • 6
  • both of the `entry` in `ctx.Update(entry)` and `ctx.Add(entry)` are the same thing. you will need to make a new copy instance of `entry`. refer to this qa on [how to make deep copy](https://stackoverflow.com/questions/78536/deep-cloning-objects). you could refer to kaffekopp answer for easier single use solution. deep copy is useful if you need to do that kind of stuff multiple times on different classes. – Bagus Tesa May 23 '22 at 11:28
  • Thank you Bagus. That is a good idea, i might try that since there are a bunch of columns which stays consistent even when the value is changed. – Nick May 23 '22 at 11:38
  • @Nick, check [this solution](https://stackoverflow.com/a/69179650/10646316). It handles versions by overriding `SaveChanges`. – Svyatoslav Danyliv May 23 '22 at 12:30
  • Use temporal tables. – Gert Arnold May 28 '23 at 09:02

2 Answers2

3

Separate your entity references, there is no reason to re-use it.

foreach (Model data in Data)
{
   // Update the entity
   var entry = context.table.Where(x => x.id == data.id).FirstOrDefault();
   entry.ValidTo = DateTime.Now;

   // Add a new entry
   ctx.Add(new Entry
   {
        // what you need for the new entry
   });
}

// Save the changes within a single transaction
ctx.SaveChanges();
kaffekopp
  • 2,551
  • 6
  • 13
  • Thank you Kaffekopp, yea it is probaly better to just create new objects. It was just convenient to reuse the old ones, since there are a bunch of supplementary data (Names,currencies and so on) which stays the same, so i wouldn't have to copy all of those. – Nick May 23 '22 at 11:35
-2

Please try using UpdateRange and AddRange method once.

    var entry = Context.table.Where(x => Data.Select(y => y.id).Contains(x.id)).ToList();
    entry = entry.ForEach(res =>
    {
        res.ValidTo = DateTime.Now
    }).ToList();
    ctx.UpdateRange(entry);

    entry = entry.ForEach(res =>
    {
        res.ValidTo = new DateTime(9999, 12, 31);
        res.ValidFrom = DateTime.Now;
        res.Value = adjustmentmodel.Value;
    }).ToList();
    ctx.AddRange(entry);
    ctx.SaveChanges();
Nishan Dhungana
  • 831
  • 3
  • 11
  • 30