背景
由于我不熟悉使用Entity Framework,因此我首先尝试构建一些简单的东西。我开始发帖子询问如何在SQL Server中存储对象列表:
现在我已经建立了两个模型:
public class MultipleChoiceQuestion
{
[Key]
public Guid MultipleChoiceQuestionId { get; set; }
[Required]
public string Question { get; set; }
[Required]
public ICollection<PossibleChoice> PossibleChoices { get; set; }
}
public class PossibleChoice
{
[Key, Column(Order = 1), ForeignKey("MultipleChoiceQuestion")]
public Guid MultipleChoiceQuestionId { get; set; }
[Key, Column(Order = 2)]
public int ChoiceIndex { get; set; }
[Required]
public string AnswerText { get; set; }
public MultipleChoiceQuestion MultipleChoiceQuestion { get; set; }
}
在QuestionContext : DbContext
我定义了:
public DbSet<MultipleChoiceQuestion> McQuestions { get; set; }
此外,我有一个Get()
端点的控制器:
[RoutePrefix("api/McQuestion")]
public class McQuestionController : ApiController
{
[AllowAnonymous]
[Route("")]
public IEnumerable<MultipleChoiceQuestion> Get()
{
var context = new QuestionContext();
return context.McQuestions;
}
}
问题
当我发出GET
请求时,会返回以下对象。
[
{
"MultipleChoiceQuestionId": "fcaf709e-2f7d-e411-80bb-002219ac77b7",
"Question": "Which integer is a prime number?",
"PossibleChoices": null
},
{
"MultipleChoiceQuestionId": "20159ee7-2f7d-e411-80bb-002219ac77b7",
"Question": "Who is the person invented light bulbs?",
"PossibleChoices": null
}
]
如何在PossibleChoices
结果中添加GET
集合?
答案 0 :(得分:1)
使用context.McQuestions.Include(“PossibleChoices”)。ToList();
但是,你需要以正确的方式学习做事,所以最好考虑一下:
1-使用Fluent API将您的实体映射到您的表,如果您已经有数据库,可以使用一些工具自动生成您的实体(POCO)类,选中“EF 6 Tools Designer”或“{{3 }}”。
2-从您的Web API返回DTO而不是直接返回实体,并在实体和DTO之间进行映射,您可以使用EF Reverse POCO generator。