2

I would like to embed foreign key objects into my .NET JSON responses in my API. I come from a Rails background and formatting the JSON response to include any found foreign key records is fairly simple. However, I can't seem to find the way to do this. I have a foreign key relationship set up like the below models:

public class Person
{
[Key]
public int id {get; set;}
public string name {get; set;}
}

public class House
{
[Key]
public int id {get; set;}
public string address {get; set;}
[Required]
public int personId {get; set;}
[ForeignKey("peronsId")]
public Person person {get; set;}
}

However, when I run a GET request, I get the house in the form:

{
"id":1,
"address":"Middle of Nowhere",
"personId":3
}

When what I want is:

{
"id":1,
"address":"Middle of Nowhere",
"person":{
"id":3,
"name":"Some Dude"
}
}

Or some similar structure. How can I accomplish this in .NET?

Using .NET 4.5 Web API 2 with Entity Framework in C#.

1 Answer 1

2

Try making the navigation property virtual:

public class House
{
  //...
  [ForeignKey("peronsId")]
  public virtual Person person {get; set;}
}

If you have not disabled the lazy loading behavior,EF automatically loads a related entity when the navigation property for that entity is dereferenced.

Another option is eager load the navigation property using the Include extension method:

datacontext.Houses.Include(h=>h.person);

I suggest you check this link for more info about this topic

Sign up to request clarification or add additional context in comments.

Comments

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.