【发布时间】:2017-07-26 11:00:50
【问题描述】:
当我使用没有外键的 JsonResult 从我的数据库(EntityFramework)发送一个对象时,我得到了我需要的结果。如果此对象包含 ForeignKey 关系,则该关系不在生成的 json 中:
我得到了什么:
{
"agentId":"9990447f-6703-11e7-9c8b-94de80ab7fee",
...
"configurationId": 22,
"configuration": null
}
我需要什么:
{
"agentId":"9990447f-6703-11e7-9c8b-94de80ab7fee",
...
"configurationId": 22,
"configuration": {
"id": 0,
...
}
}
我可以做些什么来在我的 json 中保留这个外键关系?
我已经尝试设置以下内容:
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All);
EF 上下文:
public class Agent
{
[Key]
public Guid AgentId { get; set; }
...
public int? ConfigurationId { get; set; }
[ForeignKey("ConfigurationId")]
public Configuration Configuration { get; set; }
}
public class Configuration
{
public int Id { get; set; }
...
public ICollection<Agent> Agents { get; set; }
}
控制器:
[HttpGet]
public JsonResult Index()
{
var agentList = _databaseContext.Agents;
return new JsonResult(agentList);
}
【问题讨论】:
标签: c# json asp.net-core entity-framework-core