从表中选择第一个id

时间:2014-11-03 10:21:33

标签: sql linq asp.net-mvc-4 linq-to-sql

我想根据我的子类别列出所有条目。所以我想在加载主页上显示条目列表,而不事先选择任何类别或子类别。

我做了一个返回条目列表的查询,但手动放入subCategoryId。

以下是查询:

 int userId = WebSecurity.GetUserId(User.Identity.Name);

  var preQuery = (from sub in dc.SubCategory
                  join c in dc.Category on sub.SubCategoryId equals c.Id
                  join u in dc.User on c.UserId equals u.UserId
                  where u.UserId == userId
                  select sub.SubCategoryId).Take(1).FirstOrDefault();

        var query = (from e in dc.Entry
                     join sub in dc.SubCategory on e.SubCategoryId equals sub.SubCategoryId
                     join cat in dc.Category on sub.CategoryId equals cat.Id
                     join u in dc.User on cat.UserId equals u.UserId
                     where ((u.UserId == userId) && (cat.UserId == userId) 
                         && (sub.CategoryId == cat.Id) && (e.SubCategoryId == preQuery ))
                     select e).ToList();

        return View(query);

所以我的观点是我想要而不是手动编写6的id,想要获取子类别id的列表并从中选择第一个id。我已经预先查询但仍然不是必需的结果。任何建议我做错了什么?

1 个答案:

答案 0 :(得分:1)

我能够为我的问题找到解决方案,所以我发布了解决方案。如果有人建议优化解决方案,欢迎分享。

  int userId = WebSecurity.GetUserId(User.Identity.Name);

        var preQuery = (from e in dc.Entry
                     join sub in dc.SubCategory on e.SubCategoryId equals sub.SubCategoryId
                     join cat in dc.Category on sub.CategoryId equals cat.Id
                     join u in dc.User on cat.UserId equals u.UserId
                     where u.UserId == userId
                     select e.SubCategoryId).Take(1);

        var query = (from e in dc.Entry
                     join sub in dc.SubCategory on e.SubCategoryId equals sub.SubCategoryId
                     join cat in dc.Category on sub.CategoryId equals cat.Id
                     join u in dc.User on cat.UserId equals u.UserId
                     where ((u.UserId == userId) && (cat.UserId == userId)
                         && (sub.CategoryId == cat.Id) && (e.SubCategoryId == preQuery.FirstOrDefault()))
                     select e).ToList();

        return View(query);