How to Update Existing Disconnected Entity

前端 未结 3 2036
甜味超标
甜味超标 2020-12-21 06:38

I have this code which works in EntityFrameworkCore.

public void SaveProject(Project item)
    {
        var existing = _context.Projects.FirstOrDefault(a =&         


        
相关标签:
3条回答
  • 2020-12-21 06:58

    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.

    0 讨论(0)
  • 2020-12-21 06:59

    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();
    }
    
    0 讨论(0)
  • 2020-12-21 07:06

    I created the following extension methods to update only specific values (specified in updateAction) after finding the disconnected entity by its primary key.

    Scenario: I have an ASP Core page that uses only parts of the Entity in its view and that are being transferred from/to the Web tier through DTOs that do not have all the fields

    public static T FindByPrimaryKey<T>(this DbContext context, T disconnectedEntity) where T : class
    {
        var keyValues = context.Model.FindEntityType(typeof(T)).FindPrimaryKey().Properties
            .Select(p => typeof(T).GetProperty(p.Name))
            .Select(p => p.GetValue(disconnectedEntity)).ToArray();
    
        var connectedEntity = context.Find<T>(keyValues);
    
        return connectedEntity;
    }
    
    public static void UpdateByPrimaryKey<T>(this DbContext context, T disconnectedEntity, Action<T> updateAction) where T : class
    {
        var connectedEntity = context.FindByPrimaryKey(disconnectedEntity);
    
        updateAction(connectedEntity);
    }
    
    0 讨论(0)
提交回复
热议问题