1

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

1 Answer 1

3

You can load the related data

[HttpGet]
public JsonResult Index()
{
    var agentList = _databaseContext.Agents
                                    .Include(agent=> agent.Configuration)
                                    .ToList();;
    return new JsonResult(agentList);
}
Sign up to request clarification or add additional context in comments.

3 Comments

This "kinda" works, i get the configuration object in my json. Problem is, i only get the first agent object with this and not a list of all agents.
To clarify, i can see that linq returns multiple agents but the resulting json only contains one.
I found the problem. PreserveReferencesHandling.All is still needed or include will not work. I just changed it to PreserveReferencesHandling.Object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.