复杂的ASP.NET MVC5 EF6 Linq查询

时间:2014-08-26 05:53:12

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

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

我想将整个事情转换为linq查询,但我正在努力进行支点。

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

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

我正在尝试重建的旧报告 显示实体列表及其对特定类别的每个问题的答案 ,如下所示: image http://workitonline.biz/temp/aggregation-practice_classic.png

旧代码就像这样(为了简洁而省略了很多)

'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; }
}

我有以下控制器代码来填充视图模型。

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();
    }

显然,代码在上一个查询中不起作用我不知道如何按实体和问题集合进行分组,然后在Select语句中返回一个答案列表。但直到TODO:,代码正好得到我想要的。

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

0 个答案:

没有答案