JustLearning
JustLearning

Reputation: 3322

asp mvc repository patten dealing with complex queries and viewModels

Before implementing UOW and Repository pattern i used to create conditional queries and return search results from my service layer:

For example:

`

private IQueryable<IssueSearchResult> GetIssuesQuery() {
        var query = (from iss in Dbcontext.Issues
                     join pr in Dbcontext.PurchaseRequisitions on iss.PrId equals pr.PrId
                     where iss.IssueDate>=SearchCriteria.FromDate && iss.IssueDate<=SearchCriteria.ToDate
                     select new IssueSearchResult()
                     {
                         IssueId = iss.IssueId,
                         IssueNo = iss.IssueNumber,
                         IssueDate = iss.IssueDate,
                         PrNo = pr.DocumentNumber,
                             CreatedByName = iss.User.FullName
                         });
// if(condition){
// query = query.where(etc);
//}

    return query.OrderBy(x => x.IssueId);
}
public async Task<List<IssueSearchResult>> GetAsyncIssues() {
    List<IssueSearchResult> issues = new List<IssueSearchResult>();
    try {
        issues = await GetIssuesQuery().ToListAsync();
    }
    catch (DataException) {
        throw;
    }
    return issues;
}

Now i am failling to figure out how to do the same using UOW and repository pattern as i cannot directly query entities and it is bad practice to return iqueryable from the repository.

I ve checked numerous SO post and cannot seem to find the solution.

Does it mean i should abandon Repository pattern altogether?

`

Upvotes: 0

Views: 264

Answers (1)

romandemidov
romandemidov

Reputation: 76

Your repository will contain entity framework context property, so you will use it for querying. And repository method will return you list or single object. just like i show in this small example.

 public UnitofWork : IDisposable 
{
    private DBData Context;//context you can recieve from injection or from static method 
    public IssueRepository Issues => here goes method to check that you have only one repository of this type with this context
}

public class IssueRepository{
   constructor that takes dbContext

   public async Task<List<IssueSearchResult>> GetAsyncIssues() 
{
     List<IssueSearchResult> issues = new List<IssueSearchResult>();
try {
    issues = await context.Issues.Where(expression).Select(x => new IssueSearchResult()
                 {
                     IssueId = iss.IssueId,
                     IssueNo = iss.IssueNumber,
                     IssueDate = iss.IssueDate,
                     PrNo = pr.DocumentNumber,
                         CreatedByName = iss.User.FullName
                     }).ToListAsync();
}
catch (DataException) {
    throw;
}
return issues;
}
}

Also you can use projection classes and Automapper or some other library to map results into viewmodel and back.

Upvotes: 1

Related Questions