1
          List<VideoInfo> vobj = new List<VideoInfo>();
         vobj = (from vid in db.VideoInfoes.Where(c => c.IsActive == true)
                orderby vid.VideoId  descending
                select vid
                ).ToList();
        return View(vobj);

这是带来所有视频信息列表的原始查询。还有另一个名为 profile 的表格,其中包含我需要的个人资料图片以及视频信息。所以在阅读了一篇关于 EF 的文章后,我想出了这样的事情。

  vobj = (from vid in db.VideoInfoes.Where(c => c.IsActive == true)
                 select new
                {
                 ProfileId = vid.ProfileId,
                 ProfilePictureUrl = vid.ProfileInfo.ProfilePictureUrl
                }
                orderby vid.VideoId  descending
                 select vid
                ).ToList();
        return View(vobj);

ProfileId 是外键。但这甚至没有编译..它在结束大括号和 orderby 之后显示红色语法错误。

4

2 回答 2

2

您应该这样做OrderBySelect因为您要订购的属性不包含在您的 new 中select

var vobj = (from vid in db.VideoInfoes.Where(c => c.IsActive == true)
        orderby vid.VideoId  descending
        select new
            {
             ProfileId = vid.ProfileId,
             ProfilePictureUrl = vid.ProfileInfo.ProfilePictureUrl
            }
        ).ToList();

另外,如果使用 lambda 语法,我会感觉更舒服:

var vobj = db.VideoInfoes.Where(c => c.IsActive)
          .OrderByDescending(c => c.VideoId)
          .Select(c => new {
                ProfileId = vid.ProfileId,
                ProfilePictureUrl = vid.ProfileInfo.ProfilePictureUrl
            }).ToList();
于 2013-05-05T03:42:49.253 回答
1

您的功能可以更正并变得更简单,如下所示:

return View(
   db
   .VideoInfoes
   .Where(videoInfo => videoInfo.IsActive)
   .OrderByDescending(videoInfo => videoInfo.VideoID)
   .ToList());

只要未释放连接,您就可以访问列表ProfileInfo中的每个。或者,您可以稍后在另一个查询中使用该属性访问其他记录以及另一个上下文。这取决于您想对数据做什么;(例如,我不确定该函数在做什么。)VideoInfodbProfileInfoProfileIdView

例如:

// where 'data' was what was returned from the above query
// and assuming the above 'db' connection is still open
foreach (VideoInfo videoInfo in data) 
{
   ProfileInfo profileInfo = videoInfo.ProfileInfo;

   // do something with profileInfo
}

// or if the connection was disposed:
using (MyEFModel db = new MyEFModel())
   foreach (VideoInfo videoInfo in data) 
   {
      int profileID = videoInfo.ProfileId;
      ProfileInfo profileInfo =
         db
         .ProfileInfoes
         .Single(row => row.ID == profileID);

      // do something with profileInfo
   }
于 2013-05-05T03:57:34.547 回答