asp.net核心:在JsonResult中保留ForeignKey Relation

时间:2017-07-26 11:00:51

标签: c# json asp.net-core entity-framework-core

当我使用没有外键的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);
}

1 个答案:

答案 0 :(得分:3)

您可以加载related data

[HttpGet]
public JsonResult Index()
{
    var agentList = _databaseContext.Agents
                                    .Include(agent=> agent.Configuration)
                                    .ToList();;
    return new JsonResult(agentList);
}