C# 复杂的ASP.NET MVC5 EF6 Linq查询

C# 复杂的ASP.NET MVC5 EF6 Linq查询,c#,sql,asp.net-mvc,linq,entity-framework,C#,Sql,Asp.net Mvc,Linq,Entity Framework,我正在将一个旧的经典asp(糟糕!!)应用程序转换为asp.NET MVC5 Web应用程序。 特别是一个报告是聚合,它以前是通过构建动态sql查询并在循环中执行而创建的 我想将整个过程转换为linq查询,但我正在努力完成pivot 本质上,在我的应用程序中,有许多实体(企业)从一个类别和问题集中填写一组问题,每个类别的问题数量都是动态的 问题结构: 问题集有类别,有问题(每个问题都有自己的表)。 实体通过回答和评估(在回答表中)回答问题 我试图重建的旧报告显示了一个实体列表及其对特定类别每个问

我正在将一个旧的经典asp(糟糕!!)应用程序转换为asp.NET MVC5 Web应用程序。 特别是一个报告是聚合,它以前是通过构建动态sql查询并在循环中执行而创建的

我想将整个过程转换为linq查询,但我正在努力完成pivot

本质上,在我的应用程序中,有许多实体(企业)从一个类别和问题集中填写一组问题,每个类别的问题数量都是动态的

问题结构: 问题集有类别,有问题(每个问题都有自己的表)。 实体通过回答和评估(在回答表中)回答问题

我试图重建的旧报告显示了一个实体列表及其对特定类别每个问题的答案,如下所示:

旧代码是这样的(为了breivty的缘故,我省略了很多):

'Get all the questions with filters
Dim rsQuestions : Set rsQuestions = objAuditAggregation.GetQuestionsFiltered(p_categoryId, p_questionGroupId, p_priority)

' Dynamically construct the query based on how many
' question are in the category
Dim questionValues : questionValues = ""
Dim questionTables : quesitonTables = ""

Dim totalQuestions : totalQuestions = 0

While(Not rsQuestions.EOF)  
    i = rsQuestions.Fields.Item("id").Value

    questionValues = questionValues & 
    questionTables = questionTables & 

    totalQuestions = totalQuestions + 1
    rsQuestions.MoveNext                            
Wend

'Get all the entities and their answers (filters omitted)
Set rsEntities_cmd = Server.CreateObject ("ADODB.Command")
rsEntities_cmd.ActiveConnection = MM_raworkit2004_STRING
rsEntities_cmd.CommandText = 
    "SELECT DISTINCT E.EntityId, EntityName, 
    ISNULL(EA.include, 1) AS include", a" & i & ".yourEvaluation AS yourEvaluation" & i & ", a" & i & ".yourResponse AS yourResponse" & i 
    FROM tbl0101Entity E 
    INNER JOIN tbl0102User U ON U.EntityId = E.EntityId 
    LEFT JOIN tbl12EntityAggregates EA ON E.EntityId = EA.entityId 
    LEFT JOIN (SELECT entityId, yourEvaluation, yourResponse 
           FROM tbl12Audit 
           WHERE questionId = " & i & " AND entityLevelAudit = 1) AS a" & i & " ON E.EntityId = a" & i & ".entityId"

Set rsEntities = rsEntities_cmd.Execute
因此,对于.NET代码。我有以下视图模型来显示数据:

public class AggregationPracticeConductViewModel : BaseModel
{
    public ICollection<EntitiesAndAnswersViewModel> EntitiesAndAnswers { get; set; }
    public AggregationPracticeConductFiltersViewModel Filters { get; set; }
    public bool Display { get; set; }
    public bool Updated { get; set; }
    public bool IsAdmin { get; set; }
}

public class EntitiesAndAnswersViewModel : BaseModel
{
    public Entity Entity { get; set; }
    public bool Include { get; set; }
    public ICollection<AnswersViewModel> Answers { get; set; }
}
public class AnswersViewModel
{
    public int QuestionId { get; set; }
    public int? Evaluation { get; set; }
    public int? Response { get; set; }
}
公共类聚合PracticeConductViewModel:BaseModel
{
公共ICollection实体和应答{get;set;}
公共聚合PracticeConductFiltersViewModel筛选器{get;set;}
公共布尔显示{get;set;}
公共bool更新{get;set;}
公共bool IsAdmin{get;set;}
}
公共类实体和答案视图模型:BaseModel
{
公共实体{get;set;}
公共bool包括{get;set;}
公共ICollection答案{get;set;}
}
公共类应答器VIEWMODEL
{
public int QuestionId{get;set;}
公共int?求值{get;set;}
公共int?响应{get;set;}
}
我有下面的控制器代码来填充视图模型

private ICollection<EntitiesAndAnswersViewModel> getEntitiesAndQuestions(AggregationPracticeConductViewModel apdvm, AggregationPracticeConductFiltersViewModel filters)
    {
        var query = from e in _repository.GetAll<Entity>()
                    from u in e.Users                        
                    where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId
                    select new { entity = e, user = u };

        var query2 = from a in query
                     join ea in _repository.GetAll<EntityAggregate>() on a.entity.EntityId equals ea.EntityId into eas
                     from ea in eas.DefaultIfEmpty()
                     group a.entity by new { entity = a.entity, ea = ea } into newGroup
                     orderby newGroup.Key.entity.Name
                     select new EntitiesAndAnswersViewModel()
                     {
                         Entity = newGroup.Key.entity,                            
                         Include = newGroup.Key.ea == null ? true : newGroup.Key.ea.include   // If there are no entity aggregate record yet, return as include = true                                                   
                     };                                     

         // TODO: Now join the entities with their results. This is what I have so far
        var results = from e in query2
                      join a in _repository.GetAll<ReviewAnswer>().DefaultIfEmpty() on e.Entity.EntityId equals a.entityId
                      where a.Question.Category.QuestionGroup.Id == (e.Entity.AuditQuestionGroupId != null ? e.Entity.AuditQuestionGroupId : 0)
                      && a.Question.Category.id == filters.SelectedCategoryId && a.entityLevelAudit == true
                      group e by new { e, a } into group1                          
                      select new EntitiesAndAnswersViewModel()
                      {
                          Include = group1.Key.e.Include,
                          Entity = group1.Key.e.Entity,
                          Answers =  // list of AnswersViewModels e.g. new AnswersViewModel { QuestionId = answer.question, Evaluation = answer.Evaluation, Response = answer.Response}
                      };
        return results.ToList();
    }
private ICollection获取实体和问题(聚合实践导体视图模型apdvm、聚合实践导体过滤器视图模型过滤器)
{
var query=来自_repository.GetAll()中的e
来自欧盟用户
其中(e.AuditQuestionGroupId!=null?e.AuditQuestionGroupId:0)==this.LoggedInEntity.AuditQuestionGroupId
选择新{entity=e,user=u};
var query2=来自in查询
将a.entity.EntityId等于ea.EntityId的_repository.GetAll()中的ea加入eas
来自eas.DefaultIfEmpty()中的ea
按新{entity=a.entity,ea=ea}将a.entity分组到新组中
orderby newGroup.Key.entity.Name
选择新实体和答案视图模型()
{
实体=newGroup.Key.Entity,
Include=newGroup.Key.ea==null?true:newGroup.Key.ea.Include//如果还没有实体聚合记录,则返回Include=true
};                                     
//TODO:现在将实体与它们的结果连接起来。这就是我到目前为止所做的
var结果=来自查询2中的e
在e.Entity.EntityId上的_repository.GetAll().DefaultIfEmpty()中加入一个
其中a.Question.Category.QuestionGroup.Id==(e.Entity.AuditQuestionGroupId!=null?e.Entity.AuditQuestionGroupId:0)
&&a.Question.Category.id==filters.SelectedCategoryId&&a.entityLevelAudit==true
群e由新的{e,a}组成群1
选择新实体和答案视图模型()
{
Include=group1.Key.e.Include,
实体=组1.Key.e.Entity,
答案=//答案视图模型列表,例如新答案视图模型{QuestionId=answer.question,Evaluation=answer.Evaluation,Response=answer.Response}
};
返回结果。ToList();
}
很明显,代码不像上一个查询那样工作,我不知道如何按实体和问题集分组,然后在Select语句中返回答案列表。但是直到TODO:,代码正得到我想要的

这只是最后一个查询,我甚至不确定是否可以在linq中执行。
任何帮助或指导都将不胜感激。

那么,您是否在告诉我们,讨厌的代码有效,而好的代码无效?是的,不幸的是:-(不幸的是,您已经从原始数据中删去了足够多的内容,似乎与之无关。尽管如此……没有通过LINQ进行简单的变量列查询。您可以从适当的SQL中填充
数据表