使用Repository模式 - 可以使用LINQ过滤的地方?

时间:2012-11-15 16:31:08

标签: c# .net repository repository-pattern

我最近开始在我的服务中实现Repository模式,并且我遇到了一个小问题,我想提出建议。

在我的服务中使用以下代码:

[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)]
public Policy GetPolicyById(int policyId, int historyId)
{
    // Don't do the if not deleted check here, as we can do it on our Controller.
    // This means we can use this function if we have to access the deleted records.
    return _policy.GetByID(policyId, historyId);
}

这个函数显然直接从服务接口引用,而.GetByID方法是我的通用存储库的一部分。

主要问题是:如果我想在此结果集上执行.Where(a => !a.Deleted)该怎么办?您可以通过我的代码注释看到我的一般思想是什么,但这是“正确”的做法,如果它是在服务级别,控制器(UI)级别完成,还是应该在其中创建函数我的非通用存储库允许这个功能吗?

**更新**

这是我的代码的另一部分,在我的策略存储库中:

/// <summary>
/// 
/// </summary>
/// <param name="policyId"></param>
/// <param name="historyid"></param>
/// <returns></returns>
public virtual IEnumerable<Policy> GetPolicies(int take, int skip)
{
    var policies = GetPoliciesHistoryGrouped().Take(take).Skip(skip);
    return policies;
}

/// <summary>
/// Returns all non-deleted (bitDelete) policies (in an expression, not comitted via the database), 
/// grouped by the latest history ID.
/// </summary>
/// <returns></returns>
private IEnumerable<Policy> GetPoliciesHistoryGrouped()
{
    // Group and order by history ID.
    var historyIDs = _context.Policies.Where(a => !a.bitDelete)
                     .GroupBy(a => a.intPolicyId).Select(group => new
                     {
                         PolicyID = group.Key,
                         HistoryID = group.Max(a => a.intHistoryID)
                     });
    var query = (from h in historyIDs
                 join p in _context.Policies on new { h.HistoryID, h.PolicyID } equals new { HistoryID = p.intHistoryID, PolicyID = p.intPolicyId }
                 select p).OrderBy(a => a.intPolicyId);
    return query;
}

此深度级别是否应该不在存储库层中,而应位于服务层中,其中仍然必须创建和共享GetPoliciesHistoryGrouped函数?请记住,.Take和.Skip直到分组完成后才能被调用。

1 个答案:

答案 0 :(得分:1)

你的推理是正确的。此过滤是应在服务层中完成的业务逻辑。存储库仅包含简单的CRUD方法。