Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I update Certain records in with Join and Where clause in Entity Framework Core? Using the template answer below (Attach/isModified)? 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"

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:

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 ,

Will not accept answers using Raw sql or EF Extensions for now, just Native EF Core

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
251 views
Welcome To Ask or Share your Answers For Others

1 Answer

If EF Extensions is out, what about 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. You may wish to surround the bulk operations and SaveChangesAsync in a transaction.

YMMV, I haven't used this library myself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...