我有 2 个 DTO
汽车详情Dto
public class CarDetailDto : IDto
{
public int Id { get; set; }
public string Description { get; set; }
public string ColorName { get; set; }
public string BrandName { get; set; }
public string CompanyName { get; set; }
public int ModelYear { get; set; }
public double DailyPrice { get; set; }
}
CompanyWithCarDetailDto
public class CompanyWithCarDetailDto:IDto
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public List<CarDetailDto> Cars { get; set; }
}
以及我的使用上下文=>
using (RentACarContext context = new RentACarContext())
{
var result = from company in context.Companies
join car in context.Cars
on company.Id equals car.CompanyId
join brand in context.Brands
on car.BrandId equals brand.Id
join color in context.Colors
on car.ColorId equals color.Id
where company.Id == id
select new CompanyWithCarDetailDto
{
Id = company.Id,
Name = company.Name,
Email = company.Email,
Cars = ?????????
};
}
如何在 DTO 中添加列表?
我想列出拥有汽车的公司
什么是 RentACarContext?它是数据库上下文吗,即数据库上下文?如果是这样,那么我建议它将从数据库检索数据并将数据转换为 dto 的逻辑分开。您可能需要查看实体框架中的一对多指南。
如果您遵循 EF 指南,您将获得每个公司的汽车列表。然后从数据库检索后转换它们 - 就像:
result.select(company=> new CompanyWithCarDetailDto
{
Id = company.Id,
Name = company.Name,
Email = company.Email,
Cars = company.Cars.Select(car=> new CarDetailDto
{
Id= car.Id,
Description = car.Description
.....
}
};