我想为每个食谱只获得一个文件。
var UploadedFiles = (from rec in db.Recipes
join files in db.Files on rec.Id equals files.RecipeId
select new
{
files.Id,
files.Path,
files.RecipeId,
rec.Name,
rec.Description,
rec.Category,
rec.CookTime
}).ToList();
return new JsonResult { Data = UploadedFiles, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
答案 0 :(得分:2)
您可以使用组连接而不是常规连接,我认为它也比前一个答案(使用let)更有效,尽管在这种情况下我并不完全了解EF查询优化
var UploadedFiles = (from rec in db.Recipes
join files in db.Files on rec.Id equals files.RecipeId into g
let firstFile = g.FirstOrDefault()
select new
{
firstFile.Id,
firstFile.Path,
firstFile.RecipeId,
rec.Name,
rec.Description,
rec.Category,
rec.CookTime
}).ToList();
var UploadedFiles = (from rec in db.Recipes
join files in db.Files on rec.Id equals files.RecipeId into g
let firstFile = g.FirstOrDefault()
where firstFile != null
select new
{
firstFile.Id,
firstFile.Path,
firstFile.RecipeId,
rec.Name,
rec.Description,
rec.Category,
rec.CookTime
}).ToList();
答案 1 :(得分:1)
您可以尝试以下内容......
var UploadedFiles = (from rec in db.Recipes
from files in db.Files.FirstOrDefault(f => f.RecipeId == rec.Id)
select new
{
files.Id,
files.Path,
files.RecipeId,
rec.Name,
rec.Description,
rec.Category,
rec.CookTime
}).ToList();
return new JsonResult { Data = UploadedFiles, JsonRequestBehavior =
JsonRequestBehavior.AllowGet };