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.
CodePudding user response:
I'm going to guess that:
_repo.GetSingleById(id)
looks something like:
public async Task<License> GetSingleById(int id)
=> dbContext.dbSetLicences.SingleOrDefaultAsync(item => item.Id == id);
If so then your _repo.GetSingleById(id).Include("product")
is trying to apply Include
to a Task and then you are awaiting the whole thing, which isn't going to work!
You need to do something like this:
public async ValueTask<License> GetSingleByIdAsync(int id)
=> dbContext.dbSetLicences.Include("product").SingleOrDefaultAsync(item => item.Id == id);
dbSetLicences.Include("product")
doesn't generate an IEnumerable
dataset which SingleorDefaultAsync
gets applied to. It produces an IQueryable
object that only gets executed when you call SingleorDefaultAsync
. EF will figure out the most "economic" way to generate the real Db query.
This should also work though I haven't tested it.
public async ValueTask<License> GetSingleByIdAsync(int id, bool withProduct)
{
var query = dbcontent.dbSetLicences;
if(withProduct)
query = query.Include("product")
return query.SingleOrDefaultAsync(item => item.Id == id);
}
CodePudding user response:
The error is probably because the method Include requires arguments.
e.g.
var license = await _repo.GetSingleById(id).Include(l => l.ThingIWantToInclude);