我有三个模型,它们之间的关系可以使针对他们的查询的构造变得简单,如果不是因为我目前无法控制的问题。
ModelA
数据集不需要任何相关数据。
从0..n
到ModelB
有ModelA
关系。
从0..n
到ModelC
存在ModelB
关系,但是零个或多个ModelC
可能引用API的ModelB
时存在断点访问所有ModelB
时不会返回。
dto模型格式是固定的,必须映射单个ModelA
,ModelB
和任何关联的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格式的结果集。