2 回答

TA貢獻1784條經(jīng)驗 獲得超7個贊
我將從定義 DTO 對象開始,因為直接返回數(shù)據(jù)庫對象不是最佳實踐,您通常不希望重新查看所有字段,它還為您在不破壞 API 合同的情況下更改數(shù)據(jù)庫結(jié)構(gòu)提供了更大的靈活性。此外,您需要將您的集合包裝在 Sections 屬性中,因此您不能只返回對象列表。所以,你需要這樣的結(jié)構(gòu):
public class SectionsResponse
{
public List<SectionDTO> Sections {get;set;}
}
public class SectionDTO
{
public string SectionID {get;set;}
.... add other properties
public List<ContentDTO> sectionContent {get;set;}
}
public class ContentDTO
{
... define your properties
}
下一步將是實現(xiàn)數(shù)據(jù)庫對象和 DTO 之間的映射。為此,您可以使用現(xiàn)有的庫,例如AutoMapper
至于使用數(shù)據(jù)庫,您可以應(yīng)用從實體框架急切加載。簡而言之,它看起來像:
return db.Sections.Include(x => x.Content);
或者用 DTO 和 AutoMapper 包裹:
return new SectionsResponse() { Sections = mapper.Map<List<Section>, List<SectionDTO>>(db.Sections.Include(x => x.Content)) };

TA貢獻1828條經(jīng)驗 獲得超4個贊
如果您使用的是實體框架 (EF) 并且您的表關(guān)系類型是一對多,您可以在 lambda 表達式中使用Include來返回帶有第二個表數(shù)據(jù)的第一個表。
return context.Entity1st.Include(x => x.Entity2nd);
或者你也可以這樣做:
var entities = context.Entity1st;
foreach (var entity in entities)
{
entity.Entity2nd = context.Entity2nd.Where(x => x.Entity1stId == entity.Id);
}
return entities;
- 2 回答
- 0 關(guān)注
- 225 瀏覽
添加回答
舉報