Entity Framework Core 1.0 CurrentValues.SetValues() does not exist

entity-framework-core

Question

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?

1
3
5/23/2017 10:30:17 AM

Accepted Answer

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

3
4/5/2016 12:33:38 AM

Popular Answer

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();
    }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow