为了简化为单元测试创建假数据的过程,我想要一个可以创建通用实体的函数(我将其用作许多其他类的基础对象)。该实体有一个索引,为了生成新索引,我想简单地找到当前最大的数字并加一。
我正在将 Index 用于许多其他类,并且希望使该函数尽可能通用。 我的问题是我不知道如何指定在通用函数中使用什么 DbSet GetMaxID
。
这是我到目前为止得到的:
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
有一堆不同的 IDbSets 属性,例如
public IDbSet<Customers> Customers{ get; set; }
public IDbSet<Orders> Orders{ get; set; }
等等
最佳答案
我发现我缺少 TEntity 的声明,这是通过将 where TEntity : class
附加到我的函数来修复的。我还必须更改表达式以接受 int?
以处理查询返回空值的情况。完整的功能如下(如果有人感兴趣的话)
private int GetMaxID<TEntity>(Expression<Func<TEntity, int?>> expression) where TEntity : class
{
return _repository.Set<TEntity>().Max(expression) ?? 0;
}
关于c# - Linq 表达式 : Create a max query using a generic DbSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11835526/