简体   繁体   English

C# 实体框架:使用 Where 和 Join 进行批量更新

[英]C# Entity Framework: Bulk Update with Where and Join

How do I update Certain records in with Join and Where clause in Entity Framework Core?如何使用 Entity Framework Core 中的 Join 和 Where 子句更新某些记录? Using the template answer below (Attach/isModified)?使用下面的模板答案 (Attach/isModified)? https://stackoverflow.com/a/44247720/12425844 https://stackoverflow.com/a/44247720/12425844

"If you don't want to use an SQL statement, you can use the Attach method in order to update an entity without having to load it first. As it's attached as Unchanged by default. You need to call make isModified = true " “如果您不想使用 SQL 语句,您可以使用 Attach 方法来更新实体而无需先加载它。因为它默认附加为未更改。您需要调用 make isModified = true

Current requirement:当前要求:

var data = _dbContext.Set<Product>()
    .Include(c => c.ProductType)
    .Where(x => x.Manufacturer == "ABC Company" &&
                x.StartYear == 2019 &&
                x.ProductType.ProductTypeDescription == "Electronics")

data.Manufacturer = "XYZ Company";
data.StartYear = 2020;
_dbContext.SaveChangesAsync();

Goal Code: Have to add where and join to find particular records:目标代码:必须添加 where 和 join 以查找特定记录:

https://stackoverflow.com/a/44247720/12425844 https://stackoverflow.com/a/44247720/12425844

using (myDbEntities db = new myDbEntities())
{
    try
    {
      db.Configuration.AutoDetectChangesEnabled = false;

      MyObjectEntity entityToUpdate = new MyObjectEntity() {Manufacturer = "XYZ Company", StartYear =2020};
      db.Entry(entityToUpdate).Property(e => e.Manufacturer).IsModified = true;
      db.Entry(entityToUpdate).Property(e => e.StartYear).IsModified = true;

      db.SaveChanges();
    }
    finally
    {
      db.Configuration.AutoDetectChangesEnabled = true;
    }
}

Using EF Net Core 3.1,使用 EF Net Core 3.1,

Will not accept answers using Raw sql or EF Extensions for now, just Native EF Core暂时不接受使用 Raw sql 或 EF Extensions 的答案,只接受 Native EF Core

If EF Extensions is out, what about EFCore.BulkExtensions ?如果 EF Extensions 出来了,那EFCore.BulkExtensions呢?

await _dbContext.Set<Product>()
    .Where(x => x.Manufacturer == "ABC Company" &&
                x.StartYear == 2019 &&
                x.ProductType.ProductTypeDescription == "Electronics")
    .BatchUpdateAsync(x => new Product(){
                Manufacturer = "XYZ Company",
                StartYear = 2020 });

Note update is performed as raw sql, objects loaded into the change tracker are not updated.注意更新作为原始 sql 执行,加载到更改跟踪器中的对象不会更新。 You may wish to surround the bulk operations and SaveChangesAsync in a transaction.您可能希望在事务中包含批量操作和SaveChangesAsync

YMMV, I haven't used this library myself. YMMV,我自己没用过这个库。

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

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