EF.Core.Repositories.Test.Cosmos.Container
1.2.1
dotnet add package EF.Core.Repositories.Test.Cosmos.Container --version 1.2.1
NuGet\Install-Package EF.Core.Repositories.Test.Cosmos.Container -Version 1.2.1
<PackageReference Include="EF.Core.Repositories.Test.Cosmos.Container" Version="1.2.1" />
<PackageVersion Include="EF.Core.Repositories.Test.Cosmos.Container" Version="1.2.1" />
<PackageReference Include="EF.Core.Repositories.Test.Cosmos.Container" />
paket add EF.Core.Repositories.Test.Cosmos.Container --version 1.2.1
#r "nuget: EF.Core.Repositories.Test.Cosmos.Container, 1.2.1"
#:package EF.Core.Repositories.Test.Cosmos.Container@1.2.1
#addin nuget:?package=EF.Core.Repositories.Test.Cosmos.Container&version=1.2.1
#tool nuget:?package=EF.Core.Repositories.Test.Cosmos.Container&version=1.2.1
EF.Core.Repositories
Extends Entity Framework Core to provide a Repository Pattern based on LINQ.
Installing
Install NuGet package from NuGet.org
$ dotnet add package EF.Core.Repositories
Requirements
- .NET 8 or higher
- Entity Framework Core 9.0.0 or higher
Getting Started
The Repository Factory can be registered by calling ConfigureData() extension.
The Action<DbContextOptionsBuilder> will be passed to AddDbContextFactory() extension provided by Entity Framework Core.
Note Due to the support for multiple asynchronous actions being executed against one or more repositories, multiple contexts may be created, and leveraging a DbContextFactory is required.
using EF.Core.Repositories;
...
services.ConfigureData<TContext>(opt => ...);
Within a Service/Controller/etc.
public class Consumer
{
private readonly IRepositoryFactory<TContext> _factory;
public Consumer(IRepositoryFactory<TContext> factory)
{
_factory = factory;
}
...
public async Task Command()
{
var repository = _factory.GetRepository<TEntity>();
...
}
}
Usage
IReadOnlyRepository LINQ Extensions
The majority of IQueryable Extensions are available.
- AsSingleQuery()
- AsSplitQuery()
- Distinct()
- Except()
- GroupBy()
- Include()
- Intersect()
- IntersectBy()
- Join()
- OrderBy()
- OrderByDescending()
- Select()
- SelectMany()
- Skip()
- SkipLast()
- SkipWhile()
- Take()
- TakeLast()
- TakeWhile()
- ThenBy()
- ThenByDescending()
- ThenInclude()
- Union()
- UnionBy()
- Where()
- Zip()
Include() / ThenInclude()
Just like when working with a DbSet exposed by a DbContext, you can include loading navigation properties of your entities.
Ex. Retrieving all Users, their UserRoles, and the subsequent referenced Role
var repository = _factory
.GetRepository<User>()
.Include(x => x.UserRoles)
.ThenInclude(x => x.Role);
var users = await repository.GetAsync();
IRepository/IReadOnlyRepository Async Extensions
Extensions for reading from the DbContext.
- AllAsync()
- AnyAsync()
- AverageAsync()
- CountAsync()
- FirstAsync()
- FirstOrDefaultAsync()
- GetAsync()
- Returns an IEnumerable containing the entities of the Repository.
- GetAsync(key)
- LastAsync()
- LastOrDefaultAsync()
- LongCountAsync()
- MaxAsync()
- MinAsync()
- SingleAsync()
- SingleOrDefaultAsync()
- SumAsync()
Additionally, IRepository adds the following extensions.
- DeleteAsync(entity)
- DeleteByIdAsync(key)
- InsertAsync(entity)
- UpdateAsync(entity)
GetAsync(key) and DeleteByIdAsync(key)
These functions allow you to retreive/remove an entity based upon primary key data.
Ex. Retrieving a User with a simple primary key of (int UserId)
var repository = _factory.GetRepository<User>();
var user = await repository.GetAsync(new { UserId = 5 });
Ex. Retrieving a UserRole with a complex primary key of (int UserId, int RoleId)
var repository = _factory.GetRepository<UserRole>();
var userrole = await repository.GetAsync(new { UserId = 5, RoleId = 1 });
UpdateAsync(entity)
By default UpdateAsync will ignore all navigation properties and only update the concrete data fields within the entity.
To include a navigation property as part of the update use the Include() extension.
Ex. Adding a UserRole to a User
var repository = _factory.GetRepository<User>();
var user = await repository
.Include(x => x.UserRoles)
.GetAsync(new { UserId = 5 });
user.UserRoles.Add(
new UserRole
{
UserId = 5,
RoleId = 2,
...
});
var result = await repository
.Include(x => x.UserRoles)
.UpdateAsync(user);
Transactions
Normally calls to InsertAsync or UpdateAsync immediately call SaveChangesAsync on the backing context and commit the changeset to the database.
Transactions allow for multiple changes to be committed to the database within a single SaveChangesAsync.
Example
Inserting multiple users.
using var transaction = _factory.CreateTransaction();
var repository = transaction.GetRepository<User>();
foreach (var user in users)
{
await repository.InsertAsync(user);
}
var inserted = await transaction.CommitAsync();
or
using var transaction = _factory.CreateTransaction();
var repository = transaction.GetRepository<User>();
await Task.WhenAll(
users.Select(async user =>
await repository.InsertAsync(user)));
var inserted = await transaction.CommitAsync();
Integration Testing
The EF.Core.Repositories.Test packages can be used to facilitate testing.
Supported Providers
Currently there are six data providers supported.
- Cosmos Container
- Utilizes the EntityFrameworkCore.Cosmos provider
- Uses Testcontainers.CosmosDb to create a Cosmos Db Docker Container Instance
- Each time CreateFactoryAsync() is called a new database in the Container Instance is created and seeded
- Sql Factories will automatically delete the created database when disposed.
- Failed tests will not trigger .Dispose() when factory is wrapped in a using context.
- This will cause that database to survive and be available to aid in debugging test failure.
- InMemory
- Utilizes the EntityFrameworkCore.InMemory provider
- PostgreSQL Container
- Utilizes the Npgsql.EntityFrameworkCore.PostgreSQL provider
- Uses Testcontainers.PostgreSql to create a PostgreSQL Docker Container Instance
- Each time CreateFactoryAsync() is called a new database in the Container Instance is created and seeded
- Sql Factories will automatically delete the created database when disposed.
- Failed tests will not trigger .Dispose() when factory is wrapped in a using context.
- This will cause that database to survive and be available to aid in debugging test failure.
- Sqlite
- Utilizes the EntityFrameworkCore.Sqlite provider with in memory Sqlite instances
- Sql Container
- Utilizes the EntityFrameworkCore.SqlServer provider
- Uses Testcontainers.MsSql to create a Sql Server Docker Container Instance
- Each time CreateFactoryAsync() is called a new database in the Container Instance is created and seeded
- Sql Factories will automatically delete the created database when disposed.
- Failed tests will not trigger .Dispose() when factory is wrapped in a using context.
- This will cause that database to survive and be available to aid in debugging test failure.
- Sql Instance
- Utilizes the EntityFrameworkCore.SqlServer provider
- A connection string must be passed to the builder method for use during tests
- Initial Catalog parameter will be ignored if included
- User must have create database permissions on the server
- Each time CreateFactoryAsync() is called a new database on configured server is created
- Sql Factories will automatically delete the created database when disposed.
- Failed tests will not trigger .Dispose() when factory is wrapped in a using context.
- This will cause that database to survive and be available to aid in debugging test failure.
FactoryBuilders
Each provider has an IFactoryBuilder<T> which uses a seed function to specify all objects that should be stored in the data source when it is initialized. The seeding process will automatically determine how and where to store each entity provided by the seeding function based upon the provided context.
Best practice is to initialize a builder in your constructor and then create a factory to start each test. This will result in each test using its own data source.
Examples
Using a Docker Container
Integration testing using a container is the recommended method as it does provide both an accurate representation of Database functionality and can be easily distributed.
using EF.Core.Repositories.Extensions;
using EF.Core.Repositories.Test.Extensions;
public class MyTests
{
private readonly IFactoryBuilder<MyContext> _builder;
public MyTests()
{
_builder = IFactoryBuilder<MyContext>.Instance()
.ConfigureContainerBuilder(b =>
{
// Optionally Configure Testcontainers Docker Container here
return b
.WithPassword("DbPassword")
.WithLabel("Test", "True")
.WithName("ContainerImageName");
})
.WithSeed(() => new object[]
{
new User
{
Id = 1,
Name = "Test User",
Email = "user@test.com",
}
});
}
}
Using an InMemory Provider
In Memory Providers often do not have all functionality of their full database counterparts. Usage may result in inaccurate test results.
using EF.Core.Repositories.Extensions;
using EF.Core.Repositories.Test.Extensions;
public class MyTests
{
private readonly IFactoryBuilder<MyContext> _builder;
public MyTests()
{
_builder = IFactoryBuilder<MyContext>.Instance()
.WithSeed(() => new object[]
{
new User
{
Id = 1,
Name = "Test User",
Email = "user@test.com",
}
});
}
}
Using a Sql Instance
Utilizing a physical SQL Server Instance is preferred in situations where Docker Containers are not an option. A Connection String is required for SQL Instance testing. Only Server/Security Information needs to be provided, the initial catalog will be auto-generated for each test. User will need elevated permissions to Create and Delete Databases.
using EF.Core.Repositories.Extensions;
using EF.Core.Repositories.Test.Extensions;
public class MyTests
{
private readonly IFactoryBuilder<MyContext> _builder;
public MyTests()
{
_builder = IFactoryBuilder<MyContext>.Instance()
.WithConnectionString("Server=(local);Integrated Security=true;TrustServerCertificate=true")
.WithSeed(() => new object[]
{
new User
{
Id = 1,
Name = "Test User",
Email = "user@test.com",
}
});
}
}
Full Example Test Class
Testing a UserController's Add/Update endpoints
using EF.Core.Repositories.Extensions;
using EF.Core.Repositories.Test.Extensions;
public class UserControllerTests
{
private readonly IFactoryBuilder<MyContext> _builder;
public UserControllerTests()
{
_builder = IFactoryBuilder<MyContext>.Instance()
.WithSeed(() => new object[]
{
new User
{
Id = 1,
Name = "Test User",
Email = "user@test.com",
}
});
}
[Fact]
public async void AddUser()
{
using var factory = await _builder.CreateFactoryAsync();
var controller = new UserController(factory);
var user = new User
{
Id = 2,
Name = "Test User 2",
Email = "user2@test.com",
};
var result = await controller.Add(user);
Assert.NotNull(result);
Assert.Equal(200, result.StatusCode);
}
[Fact]
public async void UpdateUser()
{
using var factory = await _builder.CreateFactoryAsync();
var controller = new UserController(factory);
var user = new User
{
Id = 1,
Name = "Test User 1",
Email = "user1@test.com",
};
var result = await controller.Update(user);
Assert.NotNull(result);
Assert.Equal(200, result.StatusCode);
}
}
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- EF.Core.Repositories (>= 1.2.1)
- Microsoft.EntityFrameworkCore.Cosmos (>= 9.0.0)
- Testcontainers.CosmosDb (>= 4.9.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.