简体   繁体   中英

EF core Update entry then Insert

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM