C#在viewModel上加载集合

时间:2018-04-03 19:49:06

标签: c# linq

我有一个viewmodel,它有一个header属性,然后是一个关联的子集合:

public int ProjectApprovalHeaderId { get; set; }

public List<ProjectApprovalStepsVM> ProjectApprovalHistorySteps{ get; set; }

我有一个返回数据的查询,如下所示:

ProjectApprovalHeaderId StepName Status
1                       Step1      A
1                       Step2      C
1                       Step3      A
2                       Step1      D

我正在尝试编写LINQ,以便我可以使用HeaderId填充viewmodel,然后使用实际的步骤数据填充子集合,但是我被卡住了。我知道这不多,但它就在我所在的地方:

var approvalHistory = from s in _context.ProjectApprovalSteps
    join u1 in _context.Users on s.AssignedApproverID equals u1.ID
    join p in _context.Projects on s.ProjectID equals p.ID
    join sc in _context.ApprovalStepStatusCodes on s.Status equals sc.StatusCode into statusList
    from scd in statusList.DefaultIfEmpty()
    where s.ProjectID == projectId
    orderby s.ProjectApprovalHeaderID, s.Sequence
           select new ProjectApprovalHistoryVM
              {
              ProjectApprovalHeaderId = s.ProjectApprovalHeaderID,
              ProjectApprovalHistorySteps = 
              };

vmApprovalHistory.ProjectApprovalHistorySteps = approvalHistory.ToList();

希望有人能指出我正确的方向。

1 个答案:

答案 0 :(得分:0)

我是Dapper的粉丝,你可以通过Nuget Install-Package Dapper安装。我推荐的原因是多映射功能。因此,像您这样的对象具有需要填充和过滤的嵌套对象。

    public IEnumerable<SpeciesModel> GetAllSpecies() => dbConnection
        .Query<SpeciesModel, SpeciesCategoryModel, SpeciesTypeModel, WetlandIndicatorModel, SpeciesModel>(getAllSpeciesQuery,
            (species, speciesCategory, speciesType, wetlandIndicator) =>
            {
                species.SpeciesCategory = speciesCategory;
                species.SpeciesType = speciesType;
                species.WetlandIndicator = wetlandIndicator;
                return species;
            });

所以上面的语法表达了嵌套对象。在返回查询时,它还会关联您的子对象。我相信这是你的意图,这样可以节省你很多时间。

使用Dapper将集合作为嵌套对象的更复杂示例。

    public IEnumerable<StemModel> GetStemModelForPlotHeader(int projectParameter, int plotParameter,
        string plantCommunityParameter) =>
        dbConnection.Query<StemModel, PlotSurveyModel, PlantCommunityModel, ProjectModel, SpeciesModel, StemModel>(getAllPlotHeaderDetails,
            (stem, survey, plantCommunity, project, species) =>
            {
                stem.PlotSurvey = survey;
                survey.PlantCommunity = plantCommunity;
                survey.Project = project;
                stem.Species = species;
                return stem;
            },
            new
            {
                ProjectId = projectParameter,
                PlantCommunityCode = plantCommunityParameter,
                PlotNumber = plotParameter
            });

<强>更新

请注意,上述答案需要您更换数据访问层。我对Dapper是公正的,因为你通过额外的映射功能获得了性能。特别是对于简单查询,但您可以利用额外的映射功能来利用性能。它还强制您的数据调用是面向SQL的,而不是生成动态查询的代码。