How to update only one field using Entity Framework?

前端 未结 16 1757
后悔当初
后悔当初 2020-11-22 09:09

Here\'s the table

Users

UserId
UserName
Password
EmailAddress

and the code..



        
16条回答
  •  日久生厌
    2020-11-22 09:44

    _context.Users.UpdateProperty(p => p.Id, request.UserId, new UpdateWrapper()
                    {
                        Expression = p => p.FcmId,Value = request.FcmId
                    });
       await _context.SaveChangesAsync(cancellationToken);
    

    Update Property is an extension method

    public static void UpdateProperty(this DbSet set, Expression> idExpression,
                T2 idValue,
                params UpdateWrapper[] updateValues)
                where T : class, new()
            {
                var entity = new T();
                var attach = set.Attach(entity);
                attach.Property(idExpression).IsModified = false;
                attach.Property(idExpression).OriginalValue = idValue;
                foreach (var update in updateValues)
                {
                    attach.Property(update.Expression).IsModified = true;
                    attach.Property(update.Expression).CurrentValue = update.Value;
                }
            }
    

    And Update Wrapper is a class

    public class UpdateWrapper
        {
            public Expression> Expression  { get; set; }
            public object Value { get; set; }
        }
    

提交回复
热议问题