Search code examples
asp.netasp.net-coreblazorrepositoryiqueryable

generic repository doesn't let me add methods


I'm building an ASP.NET Core web application. The controller use a generic repository within methods like "Get, GetById, Post, Update ecc.". When i use these methods in the controller and I try to add methods like "Include, Where ecc." pops this error : CS1501 :

"No overload for method 'method' takes 'number' arguments"

var license = await _repo.GetSingleById(id).Include("product");

i tried to return also IQueryable but it gaves me the same error.


Solution

  • GetSingleById is almost certainly returning a single item, and that means you're already past the point where you are able to use Include since the query has already been executed. So your simplest option is to pass in the Include expressions whenever you need them. First let's assume you have an existing function that looks like this:

    public async T GetSingleById(int id)
    {
        return _context.Set<T>()
            .Single(e => e.Id == id);
    }
    

    You would need to change it to something like this instead:

    public async T GetSingleById(int id, params Expression<Func<T, object>>[] includes)
    {
        IQueryable<T> query = _context.Set<T>();
    
        if(includes != null && includes.Any())
        {
            foreach(var include in includes)
            {
                query = query.Include(include);
            }
        }
    
        return query.Single(e => e.Id == id);
    }
    

    Now you can call it like this:

    // As before without any includes
    var license = await _repo.GetSingleById(id);
    
    // A single include
    var license = await _repo.GetSingleById(
        id, 
        e => e.Product);
    
    // Multiple includes
    var license = await _repo.GetSingleById(
        id, 
        e => e.Product, 
        e => e.SomethingElse);
    

    Note that I have specifically used the lambda syntax for includes rather than the string overload. These are much safer to use since they give you compile-time checking.