简体   繁体   English

对于代码优先EF将此SQL转换为lambda

[英]Convert this SQL to lambda for Code-First EF

I have this SQL, which produces the desired results: 我有此SQL,它将产生所需的结果:

select * from Categories as c
inner join Questions as q on c.Id = q.CategoryId
inner join Surveys as s on s.Id = q.SurveyId
where s.RoleId = 2

I would like to convert it to a lambda expression. 我想将其转换为lambda表达式。

How it works: 这个怎么运作:

  • A single survey exists for each user role 每个用户角色都有一个调查
  • A survey contains questions 调查包含问题
  • Sets of questions belong to a single category 问题集属于一个类别

I am trying to pull the entire survey, walking through the results with Category.Questions, etc (loop already constructed). 我正在尝试进行整个调查,使用Category.Questions等结果(已构建循环)浏览结果。

Any help on this would be appreciated, as I'm trying to get back into the .NET scene after more than 5 years of avoidance... Thank you in advance. 在此方面的任何帮助将不胜感激,因为在尝试了5年以上的尝试之后,我正努力重返.NET领域……谢谢您。

Something like this if you meant LINQ: 如果您要使用LINQ,则类似以下内容:

var query = (from c in dataContext.Categories
                  join q in dataContext.Questions on q.CategoryId = c.Id
                  join s in dataContext.Surveys on q.SurveyId = s.Id
             where c.RoleId = 5
             select new
             {
                [Your Fields]
             });

for this specific query I would persaonally prefer writing as as a LINQ without lambada expression 对于这个特定的查询,我会一直喜欢将其编写为不带lambada表达式的LINQ

var query=(from c in db.Categories  from q in Questions from n in Surveys where c.Id ==
q.CategoryId && q.SurveyId==n.Id && n..RoleId == 2).ToList();

Solved this by using: 通过使用以下方法解决了这个问题:

List<Question> questions = db.questions.Where(q => q.Survey.RoleId == iroleId).ToList();

And filtered the result set within my view, with: 并使用以下方法过滤了我认为的结果集:

foreach (Tracker.Models.Category category in Model.Select(x => x.Category).Distinct().ToList())
{
  ...
  foreach (Tracker.Models.Question question in Model.Where(x => x.Survey.RoleId == ViewBag.UserRoleId && x.CategoryId == catLoop.Id).ToList())

Seems a little messier than I expected, but the solution works. 似乎比我预期的要混乱一些,但是该解决方案有效。 There's got to be a better way than this, though... 不过,有比这更好的方法了...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM