如何反序列化列表中的子元素



我将返回从数据库中获得的数据,如下所示。

我可以获得BusPersonals的值,如下所示。我该如何以最短的方式处理这个问题?因为我在BusPersonals中有太多字段。我不想用Select一个接一个地获取所有值。我可以在不使用autoMapper的情况下处理此问题吗?

public Task<BusApiDto> DetailBus(int id)
{
var firstTable = dbContext.Bus.Where(x => x.Id == id).FirstOrDefaultAsync();
var secondTable = dbContext.BusPersonals.Where(x => x.BusId == id).ToListAsync();
//The `firstTable` is for example as follows
BusName : "Yellow Bus",
BusVehicle: "07506",
// The `secondTable` is for example as follows
FirstName = "Jack",
LastName = "Jrs",
BestColors = ["Red", "Blue", "Black"]
Foods = [{"Allergy": false, "Food": "Fish"}, {"Allergy": false, "Food": "Beef"}, 
{"Allergy": true, "Food": "Nuts"}
FirstName = "John",
LastName = "Travolta",
BestColors = ["Pink", "Blue", "Black"]
Foods = [{"Allergy": true, "Food": "Fish"}, {"Allergy": false, "Food": "Beef"}, 
{"Allergy": true, "Food": "Nuts"}
BusApiDto busApiDto = new BusApiDto ()
{
BusName = firstTable.BusName;        
BusVehicle = firstTable.BusVehicle;
BusPersonals = secondTable.Select(x => new PersonalApiDto()
FirstName = x.FirstName,
LastName = x.LastName,
BestColors = JsonConvert.DeserializeObject<List<string>>(x.BestColors),
Foods = JsonConvert.DeserializeObject<List<FoodsApiDto>>(x.Foods),
{
}).ToList();
};
return busApiDto;
}
// BusApiDto
public string BusName { get; set; }
public string BusVehicle { get; set; }
public List<BusPersonalApiDto> BusPersonals{ get; set; }
// PersonalApiDto
public string FirstName { get; set; }
public string LastName { get; set; }
public List<string> BestColors { get; set; }
public List<FoodsApiDto> Foods { get; set; }
// FoodsApiDto
public bool Allergy { get; set; }
public string Food { get; set; }
var firstTable = dbContext.Bus.Where(x => x.Id == id).FirstOrDefaultAsync();
var secondTable = dbContext.BusPersonals.Where(x => x.BusId == id).ToListAsync();
List<BusPersonalApiDto> personels = new List<BusPersonalApiDto>();
foreach(var personel in secondtable)
{       
List<FoodsApiDto> foods = new List<FoodsApiDto>();
foreach(var food in personel.Foods)
{
foods.add(new FoodsApiDto(){
Allergy = food.Allergy,
Food = food.Food
});
}
personels.add(new BusPersonalApiDto{
FirstName = person.FirstName,
LastName = person.LastName,
Foods = foods
});

}
BusApiDto busApiDto = new BusApiDto(){
BusName = firstTable.BusName,
BusVehicle = firsTable.BusVehicle,
BusPersonals = personels
};
return busApiDto;

最新更新