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

ⅰ亾dé卋堺 提交于 2019-12-01 06:18:52

问题


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:


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




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


来源:https://stackoverflow.com/questions/36369233/entity-framework-core-1-0-currentvalues-setvalues-does-not-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!