Home > Mobile >  Best practice to update large entities in EF Core update
Best practice to update large entities in EF Core update

Time:02-02

I have a table with around 50 columns.

So with EF Core that means every columns is a property. Now the user have an edit button on the UI to edit around 40 of the 50 properties. I need to update the entity like this:

oldEntity.Property1 = newEntity.Property1;
oldEntity.Property2 = newEntity.Property2;

Of course the properties have correct names and sometimes are inhertited etc.

What is the best way to do it without writing all properties down?

CodePudding user response:

According to the comment of Ghassen, you can attach the newEntity with the Key of the oldEntity in a new DbContext

        // entites
        SampleObject oldEntity = new SampleObject() { Property1 = "oldEntity", Property2 = "oldEntity2" };
        SampleObject newEntity = new SampleObject() { Property1 = "new Value", Property2 = "new Value 2" };
        
        // save oldEntity
        using var db = new ApplicationContext();
        db.Database.EnsureDeleted();
        db.Database.EnsureCreated();
        db.Add(oldEntity);
        db.SaveChanges();

        // retrieve the ID of the oldEntity
        var oldEntityId = db.SampleObject.Where(x => x.Property1 == "oldEntity").Select(x => x.Id).FirstOrDefault();

        // use new DbContext(!) and overwrite oldEntity with newEntity
        using var db2 = new ApplicationContext();
        newEntity.Id = oldEntityId;
        db2.Update(newEntity);
        db2.SaveChanges();

Maybe not elegant, but might be good enough.

CodePudding user response:

//if greaterThan  4 records then below code will perform bulk update.
public async Task PerfromOperations(IEnumerable<Employees> emps){

foreach(var emp in emps){
_dbcontext.Employee.Update(emp);

}
_dbcontext.SaveChangesAsync();

}
  • Related