3

I'm attempting to update an entity and its related child entities using Entity Framework Core 1.0 RC 1, where the entities are detached from DbContext. I've done this previously using a solution similar to the one described in this answer.

However, it seems that we are no longer able to do the following using Entity Framework 7:

DbContext.Entry(existingPhoneNumber).CurrentValues.SetValues();

Visual Studio complains that:

EntityEntry does not contain a definition for 'CurrentValues' etc...

I presume this means that this has not (yet?) been implemented for EF Core 1.0? Apart from manually updating the properties, is there any other solution?

Community
  • 1
  • 1
Blake Mumford
  • 17,201
  • 12
  • 49
  • 67

2 Answers2

3

As you have noticed, this API is not implemented yet in EF Core. See this work item: https://github.com/aspnet/EntityFramework/issues/1200

natemcmaster
  • 25,673
  • 6
  • 78
  • 100
2

I know this is an old question but I ran into this issue today, and it appears it still isn't implemented in EF Core. So I wrote an extension method to use in the meantime that will update any object's properties with the matching values of any other object.

public static class EFUpdateProperties
{
    public static TOrig UpdateProperties<TOrig, TDTO>(this TOrig original, TDTO dto)
    {
        var origProps = typeof(TOrig).GetProperties();
        var dtoProps = typeof(TDTO).GetProperties();

        foreach(PropertyInfo dtoProp in dtoProps)
        {
            origProps
                .Where(origProp => origProp.Name == dtoProp.Name)
                .Single()
                .SetMethod.Invoke(original, new Object[] 
                    { 
                    dtoProp.GetMethod.Invoke(dto, null) });                
                    }
                );                

        return original;
    }
}

Usage:

public async Task UpdateEntity(EditViewModel editDto)
    {
        // Get entry from context
        var entry = await _context.Items.Where(p => p.ID == editDto.Id).FirstOrDefaultAsync();                

        // Update properties
        entry.UpdateProperties(editDto);

        // Save Changes
        await _context.SaveChangesAsync();
    }
Alex Young
  • 4,009
  • 1
  • 16
  • 34