对MongoDB Generic Repository使用UpdateDefinition <tentity>

时间:2017-06-22 08:45:22

标签: c# .net mongodb repository

我正在尝试为mongodb创建一个通用存储库,并按照以下示例进行操作:https://github.com/alexandre-spieser/mongodb-generic-repository

这就是我所拥有的:

通用界面:

public interface IGenericRepository<TEntity> where TEntity : class, new()
{
    /// <summary>
    /// Generic Get One Async method
    /// </summary>
    /// <typeparam name="TEntity">TEntity</typeparam>
    /// <param name="id"></param>
    /// <returns></returns>
    Task<GetOneResult<TEntity>> GetOneAsync(Guid id);
}

通用实施

public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class, new()
{
    private readonly StorageContext _context = null;

    public GenericRepository(StorageContext context)
    {
        _context = context;
    }

    public async Task<Result> UpdateOneAsync(Guid id, UpdateDefinition<TEntity> update)
    {
        var filter = new FilterDefinitionBuilder<TEntity>().Eq("Id", id);
        return await UpdateOneAsync(filter, update);
    }

    public async Task<Result> UpdateOneAsync(FilterDefinition<TEntity> filter, UpdateDefinition<TEntity> update)
    {
        var result = new Result();
        try
        {
            var collection = GetCollection<TEntity>();
            var updateRes = await collection.UpdateOneAsync(filter, update);
            if (updateRes.ModifiedCount < 1)
            {
                var ex = new Exception();
                result.Message = ex.ToString();
                return result;
            }
            result.Success = true;
            result.Message = "OK";
            return result;
        }
        catch (Exception ex)
        {
            result.Message = ex.ToString();
            return result;
        }
    }
}

继承存储库

public class FileRepository : GenericRepository<File>, IFileRepository
{
    private readonly StorageContext _context = null;
    public FileRepository(StorageContext context) : base(context)
    {
        _context = context;
    }
}

正如您在通用存储库的实现中所看到的,有一个参数UpdateDefinition<TEntity> update。不应该由我的FileRepository自动设置此参数,以便在我的服务中我不必设置它吗? 如果那是不可能的,我该如何在我的服务中调用它?

await _fileRepository.UpdateOneAsync(fileId, ???);

1 个答案:

答案 0 :(得分:3)

应该像这样工作:

var update = Builders<BsonDocument>.Update
    .Set("cuisine", "American (New)")
    .CurrentDate("lastModified");
var result = await _fileRepository.UpdateOneAsync(fileId, update);