In order to simplify creating fake data for unit testing, I want to have a function that can create a generic Entity (which I use as an underlying object for a lot of other classes). The entity has an index, and, for generating a new index, I want to simply find the currently highest number and add one.
I am using Index for a lot of other classes, and would like to make this function as generic as possible. My problem is that I don't know how to specify what DbSet to use in my generic function GetMaxID
.
This is what I got so far:
private Entity CreateGenericEntity()
{
return new Entity()
{
Guid = Guid.NewGuid(),
Index = GetMaxID<Entity>(x => x.Index) + 1,
};
}
private int GetMaxID<TEntity>(Expression<Func<TEntity, int>> expression)
{
return _repository.Set<TEntity>().Max(expression);
}
_repository
has a bunch of different IDbSets properties, such as
public IDbSet<Customers> Customers{ get; set; }
public IDbSet<Orders> Orders{ get; set; }
etc.
I found that I was missing the declaration of TEntity, which was fixed by appending where TEntity : class
to my function. I also had to change the expression to accept int?
in order to handle the case where the query returns a null value. The complete function looks like this (if anyone is interested)
private int GetMaxID<TEntity>(Expression<Func<TEntity, int?>> expression) where TEntity : class
{
return _repository.Set<TEntity>().Max(expression) ?? 0;
}