grinderke grinderke - 3 months ago 66
ASP.NET (C#) Question

ASP.NET convert IQueryable to List

I've got the following code with the following error:


Error 1 Cannot implicitly convert type
'System.Linq.IQueryable<Receptura_v4.Models.ReceptDTO>'
to
'Receptura_v4.Models.ReceptDTO'
. An explicit conversion exists (are
you missing a cast?)


Any ideas how to solve it?

public ReceptDTO GetReceptForUser(string userId)
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
var q = from r in db.Recipes where r.UserId == userId select new ReceptDTO
{
RecipeID = r.RecipeID,
Title = r.Title,
Portion = r.Portion,
Time = r.Time,
Category = r.Category,
Preparation = r.Preparation,
Difficulty = r.Difficulty,
Views = 0,
Price = r.Price,
Date = DateTime.Now,
UserId = userId
};
return q;
}
}

Answer

The error means that your return type and what you are returning do not match. Your return type is ReceptDTO and you are returning a type of IQueryable<ReceptDTO>

You can return the a ReceptDTO object by sending back the First Object from the IQueryable

public ReceptDTO GetReceptForUser(string userId)
{
    using (ApplicationDbContext db = new ApplicationDbContext())
    { 
        var q = from r in db.Recipes where r.UserId == userId select new ReceptDTO
            {
                 RecipeID = r.RecipeID,
                 Title = r.Title,
                 Portion = r.Portion,
                 Time = r.Time,
                 Category = r.Category,
                 Preparation = r.Preparation,
                 Difficulty = r.Difficulty,
                 Views = 0,
                 Price = r.Price,
                 Date = DateTime.Now,
                 UserId = userId
            };
        return q.FirstOrDefault();
    }
}

If you need to return a list, you can change your method return type and return a list of ReceptDTO

public List<ReceptDTO> GetReceptForUser(string userId)
{
    using (ApplicationDbContext db = new ApplicationDbContext())
    { 
        var q = from r in db.Recipes where r.UserId == userId select new ReceptDTO
            {
                 RecipeID = r.RecipeID,
                 Title = r.Title,
                 Portion = r.Portion,
                 Time = r.Time,
                 Category = r.Category,
                 Preparation = r.Preparation,
                 Difficulty = r.Difficulty,
                 Views = 0,
                 Price = r.Price,
                 Date = DateTime.Now,
                 UserId = userId
            };
        return q.ToList();
    }
}