Thomas Schneiter Thomas Schneiter - 1 year ago 114
JSON Question

asp.net core: Preserve ForeignKey Relation in JsonResult

When i send an object from my database (EntityFramework) using JsonResult without foreign key i get the result i need. If this object contains a ForeignKey relation the relation is not in the resulting json:

What i get:

{
"agentId":"9990447f-6703-11e7-9c8b-94de80ab7fee",
...
"configurationId": 22,
"configuration": null
}


What i need:

{
"agentId":"9990447f-6703-11e7-9c8b-94de80ab7fee",
...
"configurationId": 22,
"configuration": {
"id": 0,
...
}
}



What can i do to preserve this foreign key relation in my json?


I already tried to set the following:

services.AddMvc().AddJsonOptions(options => options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All);


EF Context:

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; }
}


Controller:

[HttpGet]
public JsonResult Index()
{
var agentList = _databaseContext.Agents;
return new JsonResult(agentList);
}

Answer Source

You can load the related data

[HttpGet]
public JsonResult Index()
{
    var agentList = _databaseContext.Agents
                                    .Include(agent=> agent.Configuration)
                                    .ToList();;
    return new JsonResult(agentList);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download