Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using UpdateDefinition<TEntity> for MongoDB Generic Repository

I'm trying to create a generic repository for mongodb, and followinf this example : https://github.com/alexandre-spieser/mongodb-generic-repository

This is what I have:

Generic Interface:

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);
}

Generic Implemendation

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;
        }
    }
}

Inherit repository

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

As you can see in the implementation of the generic repository there is a parameter UpdateDefinition<TEntity> update. Shouldn't this parameter be automatically set by my FileRepository so that in my service i do not have to set it? If that is not possible, how do I call this in my service ?

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

like image 815
Gerald Hughes Avatar asked Jun 22 '17 08:06

Gerald Hughes


1 Answers

Should work like this:

var update = Builders<BsonDocument>.Update
    .Set("cuisine", "American (New)")
    .CurrentDate("lastModified");
var result = await _fileRepository.UpdateOneAsync(fileId, update);
like image 76
Gerald Hughes Avatar answered Oct 18 '22 11:10

Gerald Hughes