Chris Dixon
Chris Dixon

Reputation: 9167

Using the Repository pattern - where is acceptable to use LINQ filtering?

I've recently started implementing the Repository pattern into my service, and I've come across a small niggle that I'd like suggestions about.

Take the following code, in my service:

[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);
}

This function is obviously referenced directly from the service interface, and the .GetByID method is part of my generic repository.

The main question is: what if I want to do a .Where(a => !a.Deleted) on this result set. You can see by my code comment what my general idea of thinking is, but is this the "correct" way of doing it, should it be done at the service level, the Controller (UI) level, or should a function be created within my non-generic repository to allow for this functionality?

** UPDATE **

This is another portion of my code, in my policies repository:

/// <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;
}

Should this level of depth should not be in the repository layer, instead be in the service layer, in which the GetPoliciesHistoryGrouped function would still have to be created and shared? Remember, .Take and .Skip cannot be called until after the Grouping has been done.

Upvotes: 1

Views: 1409

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

Your reasoning is correct. This filtering is business logic that should be done in the service layer. The repository contains only simple CRUD methods.

Upvotes: 1

Related Questions