我有以下错误的以下代码:
错误1无法将类型隐式转换
'System.Linq.IQueryable<Receptura_v4.Models.ReceptDTO>'
为'Receptura_v4.Models.ReceptDTO'
。存在显式转换(您是否缺少演员表?)
有什么想法如何解决吗?
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;
}
}
该错误表示您的退货类型与您要退回的商品不匹配。您的返回类型为,ReceptDTO
而您正在返回的类型为IQueryable<ReceptDTO>
您可以ReceptDTO
通过从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();
}
}
如果需要返回列表,则可以更改方法的返回类型并返回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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句