【问题标题】:Convert SQL statement to Linq - tools not working将 SQL 语句转换为 Linq - 工具不起作用
【发布时间】:2014-01-14 12:11:53
【问题描述】:

我的 SQL 有效;

select Question, QuestionOption.QuestionOption, Response.Answer from Questions
left join QuestionOption on (QuestionOption.QuestionId = QuestionS.Id)
left join Response on (Questions.Id = Response.QuestionId) 
Where PageNumber = 1 AND (Response.UserId = '6c61c415-1e09-4c16-82bf-fbc1b30e3c5a')

PageNumber 和 Response.UserId 是我可以从我的模型中获取的变量,但是我尝试过的 Linq 语句都没有工作,但我不确定它是我的 Linq 还是我的 ViewModel;

public class GetQuestionViewModel
{
    public virtual List<Question> Questions { get; set; }

    public int Id { get; set; }
    public int PageNumber { get; set; }
    public string Question1 { get; set; }
    public int QuestionTypeId { get; set; }
    public Nullable<int> LinkedTo { get; set; }
    public Nullable<int> Options { get; set; }
    public Nullable<int> QuestionRanking { get; set; }
    public virtual ICollection<QuestionOption> QuestionOptions { get; set; }
    public virtual QuestionType QuestionType { get; set; }
    public virtual ICollection<Response> Responses { get; set; }
    public virtual ICollection<AspNetUser> AspNetUsers { get; set; }
}

我刚刚将 public virtual List Questions 行添加到我的 ViewModel 中,但它仍然无法编译。

我不确定我的模型中是否需要 AspNetUsers,因为我正在使用 @User.Identity.GetUserId() 在隐藏字段中的视图中抓取它,但是当我将它指向 GetQuestionViewModel 时,我将它添加为我的视图中断。有人可以发布一个如何正确完成此操作的示例,或推荐一个可以为我执行此操作的工具吗? Linqer 无法正常工作,我正在等待支持人员提供解决方案。

我知道这很遥远,因为它甚至没有在 PageNumber 上产生正确的问题,并且我删除了对 Response 的所有引用,因为我什至无法使其正常工作;

    //    var question = from q in db.Questions
    //                   where q.PageNumber == pageId
    //                   orderby q.Ranking
    //                   select new Template.Models.GetQuestionViewModel( )
    //                  { questionId = q.QuestionId,
    //                    questionType = q.QuestionType,
    //                    question1 = q.Question1 };
    //    return View(question.AsEnumerable());

【问题讨论】:

  • 显示你尝试过的 Linq。

标签: c# sql asp.net-mvc linq


【解决方案1】:

DefaultIfEmpty 会将其从内连接变为左连接

var query = from q in db.Questions
            from qo in q.QuestionOptions.DefaultIfEmpty()
            from r in q.Responses.DefaultIfEmpty()
            where q.PageNumber == 1 && r.UserId == '6c61c415-1e09-4c16-82bf-fbc1b30e3c5a'
            select new Template.Models.GetQuestionViewModel( )
            { 
              questionId = q.QuestionId,
              questionType = q.QuestionType,
              question1 = q.Question1 
            };

【讨论】:

  • 我尝试了您的查询,但它不会在“问题”上编译,说没有找到“多选”模式。所以我在我的 ViewModel 中添加了一行,但是我的语法错了吗?它应该是 ICollection 而不是列表?
猜你喜欢
  • 2013-02-15
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2015-05-11
  • 2016-03-29
  • 1970-01-01
相关资源
最近更新 更多