这是我的模态类
public class Tag
{
public int Id { get; set; }
public int UnitId { get; set; }
public int MeasureId { get; set; }
public int TagTypeId { get; set; }
}
我想从表中获取数据并执行GroupBy。TagTypeId我想到的结果是这个 json 数据:
结果:
[
{
"title": "Actual",
"key": 1,
"disabled": false,
"child": [
{
"title": "valve 0036",
"key": "Tag1",
"disabled": true,
"measure": "Celsius",
"tagType": "Actual",
"child": null
},
{
"title": "valve 0036",
"key": "Tag2",
"disabled": true,
"measure": "Celsius",
"tagType": "Actual",
"child": null
},
{
"title": "valve 0036",
"key": "Tag21",
"disabled": true,
"measure": "Celsius",
"tagType": "Actual",
"child": null
}
]
},
{
"title": "Virtual",
"key": 2,
"disabled": false,
"child": [
{
"title": "valve 0036",
"key": "Tag36",
"disabled": true,
"measure": "Celsius",
"tagType": "Virtual",
"child": null
},
{
"title": "valve 0036",
"key": "Tag37",
"disabled": true,
"measure": "Celsius",
"tagType": "Virtual",
"child": null
}
]
},
{
"title": "Lab",
"key": 3,
"disabled": false,
"child": [
{
"title": "valve 0036",
"key": "Tag38",
"disabled": true,
"measure": "Celsius",
"tagType": "Lab",
"child": null
}
]
}
]
我编写此代码有效,但我被迫使用那里查询做。
var tagsDataActual = await _context
.Tags.Where(x => x.TagTypeId == 1)
.GroupBy(x => new { x.TagTypeId, x.TagType.Title })
.Select(x => new TagDto
{
Title = x.Key.Title,
Key = x.Key.TagTypeId.ToString(),
Child = _context.Tags.Where(x => x.TagTypeId == 1)
.Select(x => new TagDto
{
Title = x.Title,
Measure = x.Measure.Title,
Key = "Tag" + x.Id.ToString(),
TagType = x.TagType.Title,
Disabled = true,
Child = null
})
}).ToListAsync();
var tagsDataVirtual = await _context
.Tags
.Where(x => x.TagTypeId == 2)
.GroupBy(x => new { x.TagTypeId, x.TagType.Title })
.Select(xs => new TagDto
{
Title = xs.Key.Title,
Child = _context.Tags.Where(x => x.TagTypeId == 2)
.Select(x => new TagDto
{
Title = x.Title,
Measure = x.Measure.Title,
Key = "Tag" + x.Id.ToString(),
TagType = x.TagType.Title,
Disabled = true,
Child = null
})
}).ToListAsync();
var tagsDataLab = await _context
.Tags
.Where(x => x.TagTypeId == 3)
.GroupBy(x => new { x.TagTypeId, x.TagType.Title })
.Select(xs => new TagDto
{
Title = xs.Key.Title,
Child = _context.Tags.Where(x => x.TagTypeId == 3)
.Select(x => new TagDto
{
Title = x.Title,
Measure = x.Measure.Title,
Key = "Tag" + x.Id.ToString(),
TagType = x.TagType.Title,
Disabled = true,
Child = null
})
}).ToListAsync();
var tagsData = tagsDataActual.Concat(tagsDataVirtual).Concat(tagsDataLab).ToList();
return tagsData;
这是 TagDto 类
public class TagDto
{
public string Title { get; set; }
public string Key { get; set; }
public bool Disabled { get; set; }
public string Measure { get; set; }
public string TagType { get; set; }
public IEnumerable<TagDto> Child { get; set; }
}
有没有办法使用一个查询而不是那里?谢谢...