Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Update Existing Disconnected Entity

I have this code which works in EntityFrameworkCore.

public void SaveProject(Project item)
    {
        var existing = _context.Projects.FirstOrDefault(a => a.Id == item.Id);
        existing.Description = item.Description;
        existing.IsArchived = item.IsArchived;
        existing.IsDeleted = item.IsDeleted;
        existing.Name = item.Name;
        _context.SaveChanges();

    }

It taking a disconnected entity, finding it in the database, and applying the changes.

Is there a better way to do this?

I would like to not make a call to the database. In other words, I would like to be able to mark the entity as modified, and then call SaveChanges().

Is there a way to do that?

like image 938
Greg Gum Avatar asked Mar 12 '23 16:03

Greg Gum


2 Answers

If you are certain that item exist in database, you can use Attach method of DbContext As following

public void SaveProject(Project item)
{
    _context.Projects.Attach(item);
    _context.Entity(item).State=EntityState.Modified;
    _context.SaveChanges();
}
like image 155
Mohammad Akbari Avatar answered Mar 16 '23 02:03

Mohammad Akbari


In EntityFramework Core, it can now be done using the Update method:

 DbContext.Update<Item>(item);
 this.SaveChanges();

In version 2.1, the Update method can now be used for both new and existing entities if the Id property is auto-generated.

The Docs

The downside to this is that all properties are marked as modified, even if they are the same. The issue with this is that if you are logging changes in a database trigger, then every property will be flagged as changed, even when they are not. If you only want specific properties updated, then you need to get the entity from the database, update as desired, then save.

like image 44
Greg Gum Avatar answered Mar 16 '23 00:03

Greg Gum