简体   繁体   English

EF 核心更新条目然后插入

[英]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.所以我想更新一个条目的 Valid to 列,然后插入一个带有新值的新副本。 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.我尝试在 ctx.update(entry) 之后插入 saveChanges,这可行,但速度很慢。 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我正在使用 dotnet 5 和 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.请尝试使用 UpdateRange 和 AddRange 方法一次。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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