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

前端 未结 2 1343
陌清茗
陌清茗 2021-01-14 11:19

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 prev

相关标签:
2条回答
  • 2021-01-14 12:01

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

    0 讨论(0)
  • 2021-01-14 12:09

    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();
        }
    
    0 讨论(0)
提交回复
热议问题