Home > Blockchain >  EF core Update entry then Insert
EF core Update entry then Insert

Time:05-23

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

CodePudding user response:

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();

CodePudding user response:

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();
  • Related