Marthijn
Marthijn

Reputation: 3392

Handling entity framework relations in json.net

I have an ASP MVC Web Api project that outputs json using json.net. I have for example the following models:

public class ModelA
{
    public int Id {get;set;}
    public string Name {get;set;}

    [JsonIgnore]
    public int TypeModelId {get;set;}
    public virtual TypeModel TypeModel {get;set;}
}

public class TypeModel
{
    [JsonIgnore]
    public int Id {get;set;}

    public string Name {get;set;}

    [JsonIgnore]
    public virtual IList<ModelA> ModelAs {get;set;}
}

When I serialize a ModelA the output will be something like this:

[
  {
    "Id": 1,
    "Name": "test",
    "TypeModel": {
      "Name": "testtype1"
    }
  }
]

Is it possible using json.net to have an output like this..

[
  {
    "Id": 1,
    "Name": "test",
    "TypeModel": "testtype1"
  }
]

..or do I have to copy the contents of ModelA to a new class which stores the TypeModel relation as string instead of reference? Maybe there are better solutions?

Upvotes: 0

Views: 342

Answers (2)

L.Trabacchin
L.Trabacchin

Reputation: 1620

Actually this is not true, json.net can handle loop reference handling, dto is an old method, still good, but you can enable in the serializer the option to handle loopreferences as long as it is mvc5 and maybe also mvc4. More details here: https://stackoverflow.com/a/23044770/1345207

Upvotes: 0

Ryan Amies
Ryan Amies

Reputation: 4922

As you say the only way to do this is with a DTO. This is because, as you indicated, the type of TypeModel is a class TypeModel and not a string. If you are using Linq you could also just use an anonymous type in the following way.

return db.ModelAs.Single(x=>x.Id == id).Select(x=> new{
    x.Id,
    x.Name,
    TypeModel = x.TypeModel.Name
});

Upvotes: 1

Related Questions