Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

BaseRepository.cs 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using Diligent.WebAPI.Business.Interfaces;
  2. using Diligent.WebAPI.Data;
  3. using MongoDB.Bson;
  4. using MongoDB.Driver;
  5. namespace Diligent.WebAPI.Business.Services
  6. {
  7. public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class
  8. {
  9. protected readonly IMongoDBContext _mongoContext;
  10. protected IMongoCollection<TEntity> _dbCollection;
  11. private readonly FilterDefinitionBuilder<TEntity> _builder = Builders<TEntity>.Filter;
  12. public BaseRepository(IMongoDBContext context)
  13. {
  14. _mongoContext = context;
  15. _dbCollection = _mongoContext.GetCollection<TEntity>(typeof(TEntity).Name);
  16. }
  17. public async Task<List<TEntity>> GetAsync()
  18. {
  19. var all = await _dbCollection.FindAsync(_builder.Empty);
  20. return await all.ToListAsync();
  21. }
  22. public async Task<TEntity> GetByIdAsync(string id)
  23. {
  24. var element = await _dbCollection.FindAsync(_builder.Eq("_id", new ObjectId(id)));
  25. return await element.FirstOrDefaultAsync();
  26. }
  27. public async Task RemoveAsync(string id)
  28. {
  29. await _dbCollection.FindOneAndDeleteAsync(_builder.Eq("_id", new ObjectId(id)));
  30. }
  31. public async Task UpdateAsync(string id, TEntity updateEntity)
  32. {
  33. await _dbCollection.FindOneAndReplaceAsync(_builder.Eq("_id", new ObjectId(id)), updateEntity);
  34. }
  35. public async Task CreateAsync(TEntity entity)
  36. {
  37. await _dbCollection.InsertOneAsync(entity);
  38. }
  39. }
  40. }