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

前端 未结 2 1344
陌清茗
陌清茗 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: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(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();
        }
    

提交回复
热议问题