NHUnit 1.2.0
dotnet add package NHUnit --version 1.2.0
NuGet\Install-Package NHUnit -Version 1.2.0
<PackageReference Include="NHUnit" Version="1.2.0" />
<PackageVersion Include="NHUnit" Version="1.2.0" />
<PackageReference Include="NHUnit" />
paket add NHUnit --version 1.2.0
#r "nuget: NHUnit, 1.2.0"
#:package NHUnit@1.2.0
#addin nuget:?package=NHUnit&version=1.2.0
#tool nuget:?package=NHUnit&version=1.2.0
NHUnit
Start your first NHUnit project in a few minutes using the Example project NHUnit provides sync and async versions for each method.
Create your Unit of work
Register NHibernate.ISessionFactory into your dependency injection and define the interface for your Database.
public interface IDbContext : IUnitOfWork
{
IRepository<Customer> Customers { get; }
IRepository<Product> Products { get; }
}
public class DbContext : UnitOfWork, IDbContext
{
public DbContext(ISessionFactory sessionFactory) : base(sessionFactory, true) { }
public IRepository<Customer> Customers { get; set; }
public IRepository<Product> Products { get; set; }
}
The framework automatically initializes all your IRepository
properties when the second constructor parameter is true, otherwise you will need to do this yourself:
public DbContext(ISessionFactory sessionFactory) : base(sessionFactory) {
Customers = new Repository<Customer>();
Products = new Repository<Product>();
}
Eager loading
Using lambda expressions you can specify which child properties should be populated. The framework will determine the fastest approach to load the data: using join, future queries or by using batch fetching. Depending on the number of returned rows and the depth you might need to finetune your queries, but in most cases the framework takes the best decision.
var customer = await _dbContext.Customers.Get(customerId) //returns a wrapper to configure the query
.Include(c => c.Addresses.Single().Country, //include Addresses and Country
c => c.PhoneNumbers.Single().PhoneNumberType) //include all PhoneNumbers with PhoneNumberType
.Unproxy() //instructs the framework to strip all the proxy classes when the Value is returned
.Deferred() //instructs the framework to delay execution
.ValueAsync(token); //this is where the query(s) get executed
The expression c.Addresses.Single().Country
will load all the nested child objects.
Addresses
is a colection and you need to use Addresses.Single()
to include the nested children. The whole collection will be populated, not just the first item.
Unproxy
You can use IUnitOfWork.Unproxy, ISingleEntityWrapper.Unproxy or IEntityListWrapper.Unproxy
var customer = await _dbContext.Customers
.Get(customerId) //returns a wrapper to configure the query
.Unproxy() //instructs the framework to strip all the proxy classes when the Value is returned
.ValueAsync(token); //this is where the query(s) get executed
An unproxied object will contain the foreign key ids (One to One and Many to One relations). For example in the above query the Cart property will be instantiated and popuplated with the Id field.
Deferred Execution
Using Deferred()
you can execute multiple queries in a single server trip.
Bellow is an example with 3 different queries that get executed in one server trip.
//product count future
var prodCountP = _dbContext.WrapQuery(_dbContext.Products.All())
.Count()
.Deferred();
//most expensive 10 products future
var expProdsP = _dbContext.WrapQuery(_dbContext.Products.All().OrderByDescending(p => p.Price).Take(10))
.Deferred();
//get customer by id - executes all queries
var customer = await _dbContext.Customers
.Get(customerId)
.Deferred()
.ValueAsync();
var prodCount = await prodCountP.ValueAsync(); //returns one value
var expProds = await expProdsP.ListAsync(); //returns list
Conditional Queries
If you need to update or delete a set of records that meet a condition, you don't need to load them in memory. Just write an expression and it will be evaluated immediately.
You should always run your commands inside a transaction with BeginTransaction()
and CommitTransactionAsync
.
UpdateWhereAsync
Increase price by 5 for all products that are less than 100, without loading them in memory.
await _dbContext.Products.UpdateWhereAsync(p => p.Price < 100, p => new { Price = p.Price + 5 });
DeleteWhereAsync
Delete products that are too cheap, without loading them in memory.
await _dbContext.Products.DeleteWhereAsync(p => p.Price < 2);
Transactions
IUnitOfWork exposes:
- BeginTransaction
- CommitTransactionAsync - pushes changes and commits transaction
- RollbackTransactionAsync
- SaveChangesAsync - pushes changes to DB but doesn't commit transaction (if any)
- ClearCache - evict all loaded instances and cancel all pending saves, updates and deletions
Procedures/Queries
In some rare cases you need to execute your own queries/procedures and NHUnit provides this functionality:
- ExecuteListAsync : return a list of values
var sqlQuery = @"select Id, FirstName, LastName, BirthDate from ""Customer""";
var customers = await _dbContext.ExecuteListAsync<Customer>(sqlQuery, null, cancellationToken);
- ExecuteScalarAsync : return single value/object
var sqlQuery = @"select Id as CustomerId,
Concat(FirstName,' ',LastName) as FullName,
BirthDate
from ""Customer""
where Id= :customerId";
var customResult = await _dbContext.ExecuteScalarAsync<SqlQueryCustomResult>(sqlQuery, new { customerId = 11 });
- ExecuteNonQueryAsync : no value returned
var sqlQuery = @"update ""Product"" set price=price+1 where price< :productPrice";
await _dbContext.ExecuteNonQueryAsync(sqlQuery, new { productPrice = 5 }, cancellationToken);
- ExecuteMultipleQueriesAsync : return multiple result sets
var sqlQuery = @"select Id as CustomerId,
Concat(FirstName,' ',LastName) as FullName,
BirthDate
from ""Customer""
where Id= :customerId;
select count(*) Count from ""Customer"";";
var customResult = await _dbContext.ExecuteMultipleQueriesAsync(sqlQuery, //query
new { customerId }, //parameters: property name must be the same as the parameter
cancellationToken,
typeof(SqlQueryCustomResult), //first result type
typeof(long));//second result type
//The results are returned in order in their own collection.
var customer = (SqlQueryCustomResult)customResult[0].FirstOrDefault(); //we might not have any results
var customerCount = (long)customResult[1].First(); //the type must match
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. 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. |
.NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
.NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen40 was computed. tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- NHibernate (>= 5.3.5)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Enhancements:
- Load multiple objects by Id: IRepository.GetMany(ids)
- Return the number of affected rows for DeleteWhere and UpdateWhere
- Use existing row values in IRepository.UpdateWhereAsync