Skip to content

Commit

Permalink
Add GetAllAsync on generic repository
Browse files Browse the repository at this point in the history
  • Loading branch information
hocinehacherouf committed Oct 14, 2022
1 parent cf4dd5b commit a60afe1
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ public IEnumerable<T> GetAll()
.ToList<T>();
}

public async Task<IEnumerable<T>> GetAllAsync(Expression<Func<T, bool>>? expression = null, CancellationToken cancellationToken = default)
{
IQueryable<T> query = this.context.Set<T>();
if (expression != null) query = query.Where(expression);

return await query.ToDynamicListAsync<T>(cancellationToken: cancellationToken);
}

public virtual async Task<T?> GetByIdAsync(object id)
{
var t = await this.context.Set<T>().FindAsync(id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -355,5 +355,79 @@ await context.AddRangeAsync(new List<DeviceTag>
// Assert
_ = result.Should().BeFalse();
}

[Test]
public async Task GetAllAsync_WithFilter_AllItemsReturned()
{
// Arrange
var context = SetupDbContext();

await context.AddRangeAsync(new List<DeviceTag>
{
new()
{
Id = "device_tag_01",
Label = "Location 1",
Required = false,
Searchable = true
},
new()
{
Id = "device_tag_02",
Label = "Location 2",
Required = true,
Searchable = true
}
});

_ = await context.SaveChangesAsync();

var instance = new GenericRepository<DeviceTag>(context);

// Act
var result = await instance.GetAllAsync();

// Assert
_ = result.Count().Should().Be(2);
}

[Test]
public async Task GetAllAsync_CustomFilter_ExpectedItemsReturned()
{
// Arrange
var context = SetupDbContext();

await context.AddRangeAsync(new List<DeviceTag>
{
new()
{
Id = "device_tag_01",
Label = "Location 1",
Required = false,
Searchable = true
},
new()
{
Id = "device_tag_02",
Label = "Location 2",
Required = true,
Searchable = true
}
});

_ = await context.SaveChangesAsync();

var instance = new GenericRepository<DeviceTag>(context);

// Filter only tags with labels required
var deviceTagPredicate = PredicateBuilder.True<DeviceTag>()
.And(tag => tag.Required);

// Act
var result = await instance.GetAllAsync(deviceTagPredicate);

// Assert
_ = result.Count().Should().Be(1);
}
}
}
2 changes: 2 additions & 0 deletions src/AzureIoTHubPortal.Domain/IRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ public interface IRepository<T> where T : EntityBase
{
IEnumerable<T> GetAll();

Task<IEnumerable<T>> GetAllAsync(Expression<Func<T, bool>>? expression = null, CancellationToken cancellationToken = default);

Task<T?> GetByIdAsync(object id);

Task InsertAsync(T obj);
Expand Down

0 comments on commit a60afe1

Please sign in to comment.