Linq表达式:使用通用DbSet创建最大查询

时间:2012-08-06 20:33:42

标签: c# entity-framework lambda generic-programming dbset

为了简化为单元测试创​​建虚假数据的问题,我希望有一个可以创建通用实体的函数(我将其用作许多其他类的底层对象)。该实体有一个索引,并且,为了生成一个新索引,我想简单地找到当前最高的数字并添加一个。

我正在为很多其他类使用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; }

1 个答案:

答案 0 :(得分:1)

我发现我错过了TEntity的声明,这是通过将where TEntity : class附加到我的函数来修复的。我还必须将表达式更改为接受int?,以便处理查询返回空值的情况。完整的功能看起来像这样(如果有人有兴趣)

private int GetMaxID<TEntity>(Expression<Func<TEntity, int?>> expression) where TEntity : class
{
    return _repository.Set<TEntity>().Max(expression) ?? 0;
}