NET核心MongoDB的更新/更换排除领域

问题描述 投票:1回答:1

我试图完成对所有实体的一般存储库在我的应用程序。我和财产BaseEntityIdCreatorId一个LastModifiedUserId。现在我想更新集合中的记录,而不必修改字段CreatorId,所以我有(从客户端)的实体增值的一些领域的更新,我想更新。喜有2种方式:

  1. UpdateOneAsync
  2. ReplaceOneAsync

回购创建这样的:

public class BaseRepository<T> : IRepository<T> where T : BaseEntity 
{
   public async Task<T> Replace/Update(T entity){...}
}

所以这是非常难用更新(1),因为我应该反思检索的T所有字段和排除我不希望更新的。替换为(2)我无法找到一个方法来指定哪些字段与另一个替换对象时,我应该排除。 Projectionproperty在FindOneAndReplaceOptions<T>()只是排除在被更新后返回的文件中的字段。

我缺少的方式在replace方法排除字段或者我应该尝试检索与反思的领域和使用Update

mongodb .net-core repository mongodb-.net-driver
1个回答
0
投票

我不知道,如果这个解决方案是确定你..我要做的就是:

声明在基地回购等的方法

 public virtual bool Update(TEntity entity, string key)
        {
            var result = _collection.ReplaceOne(x => x.Id.Equals(key), entity, new UpdateOptions
            {

                IsUpsert = false
            });

            return result.IsAcknowledged;
        }

那么,当你想更新实体控制器有你设置你想改变的道具..喜欢:

  [HttpPut]
    [ProducesResponseType(typeof(OrderDTO), 200)]
    [ProducesResponseType(400)]
    public async Task<ActionResult<bool>> Put([FromBody] OrderDTO value)
    {
        try
        {
            if (!ModelState.IsValid) return BadRequest(ModelState);

            var orderOnDb = await _orderService.FindAsync(xx => xx.Id == value.Id);
            if (orderOnDb == null) return BadRequest(Constants.Error.NOT_FOUND_ON_MONGO);


            // SET PROPERTY TO UPDATE (MANUALLY)
            orderOnDb.LastUpdateDate = DateTime.Now;
            orderOnDb.PaymentMethod = value.PaymentMethod;
            orderOnDb.StateHistory = value.StateHistory;

            //Save on db
            var res = await _orderRepo.UpdateAsync(orderOnDb, orderOnDb.Id);

            return res;

        }
        catch (Exception ex)
        {
            _logger.LogCritical(ex, ex.Message);
            throw ex;
        }
    }

希望它可以帮助你!

© www.soinside.com 2019 - 2024. All rights reserved.