针对损坏的源数据集构造linq查询

时间:2019-04-27 22:09:43

标签: c# linq

我有三个模型,它们之间的关系可以使针对他们的查询的构造变得简单,如果不是因为我目前无法控制的问题。

ModelA数据集不需要任何相关数据。

0..nModelBModelA关系。

0..nModelC存在ModelB关系,但是零个或多个ModelC可能引用API的ModelB时存在断点访问所有ModelB时不会返回。

dto模型格式是固定的,必须映射单个ModelAModelB和任何关联的ModelC。对于破损的情况,ModelB必须为空。

using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        var modelAs = new[]
        {
            new ModelA { Id = 0, Name = "ModelA0" },
            new ModelA { Id = 1, Name = "ModelA1" },
            new ModelA { Id = 2, Name = "ModelA2" },
            new ModelA { Id = 3, Name = "ModelA3" },
            new ModelA { Id = 4, Name = "ModelA4" }
        };

        var modelBs = new[]
        {
            new ModelB { Id = 0, ModelAId = 1, Name = "ModelB0" },
            new ModelB { Id = 1, ModelAId = 3, Name = "ModelB1" },
            new ModelB { Id = 2, ModelAId = 4, Name = "ModelB2" },
        };

        var modelCs = new[]
        {
            new ModelC { Id = 0, ModelAId = 0, ModelBId = 3, Name = "ModelC0" },
            new ModelC { Id = 1, ModelAId = 0, ModelBId = 3, Name = "ModelC1" },
            new ModelC { Id = 2, ModelAId = 0, ModelBId = 3, Name = "ModelC2" },
            new ModelC { Id = 3, ModelAId = 1, ModelBId = 1, Name = "ModelC3" },
            new ModelC { Id = 4, ModelAId = 1, ModelBId = 1, Name = "ModelC5" },
            new ModelC { Id = 5, ModelAId = 2, ModelBId = 2, Name = "ModelC5" }
        };

        var query =
            from modelA in modelAs
            join modelB in modelBs on modelA.Id equals modelB.ModelAId into modelBGroup
            join modelC in modelCs on modelA.Id equals modelC.ModelAId into modelCGroup
            where modelBGroup.Any() || modelCGroup.Any()
            orderby modelA.Id
            select new { modelA, modelBGroup, modelCGroup };
    }
}

public class ModelA
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class ModelB
{
    public int Id { get; set; }
    public int ModelAId { get; set; }
    public string Name { get; set; }
}

public class ModelC
{
    public int Id { get; set; }
    public int ModelAId { get; set; }
    public int ModelBId { get; set; }
    public string Name { get; set; }
}

public class ModelDto
{
    public ModelA ModelA { get; set; }
    public ModelB ModelB { get; set; }
    public ModelC[] ModelCs { get; set; }
}

我可以手动构造结果集,但是它比我确信的要冗长得多。是否存在可以使用简洁格式组装dto的查询?我进行的查询只是部分尝试,但是未能生成可以合理地映射到dto格式的结果集。

0 个答案:

没有答案