How to Get Full Object with Code First Entity Framework 4.1
I am trying to return as JSON the fully deep object (with all of the foreign key relationships filled in) but I am getting nulls for all the referenced objects.
Here is the call to get the object:
public ActionResult GetAll()
{
return Json(ppEFContext.Orders, JsonRequestBehavior.AllowGet);
}
And here is the Order object itself:
public class Order
{
public int Id { get; set; }
public Patient Patient { get; set; }
public CertificationPeriod CertificationPeriod { get; set; }
public Agency Agency { get; set; }
public Diagnosis PrimaryDiagnosis { get; set; }
public OrderApprovalStatus ApprovalStatus { get; set; }
public User App开发者_如何转开发rover { get; set; }
public User Submitter { get; set; }
public DateTime ApprovalDate { get; set; }
public DateTime SubmittedDate { get; set; }
public Boolean IsDeprecated { get; set; }
}
I have not yet found a good resource on using EF 4.1 Annotations. If you could suggest a good one, that has the answer, you could give me the link and that would be enough of an answer for me!
Regards,
Guido
Update
I added the virtual keyword as per Saxman and am now dealing with the circular reference error issue.
Add the virtual
keyword before your related entities:
public class Order
{
public int Id { get; set; }
public virtual Patient Patient { get; set; }
public virtual CertificationPeriod CertificationPeriod { get; set; }
public virtual Agency Agency { get; set; }
public virtual Diagnosis PrimaryDiagnosis { get; set; }
public virtual OrderApprovalStatus ApprovalStatus { get; set; }
public virtual User Approver { get; set; }
public virtual User Submitter { get; set; }
public DateTime ApprovalDate { get; set; }
public DateTime SubmittedDate { get; set; }
public Boolean IsDeprecated { get; set; }
}
You might end up with a A circular reference was detected while serializing an object...
error if your objects have references of each other. In that case, you will need to create a ViewModel
or something similar to overcome this problem. Or use LINQ to project an anonymous object.
Read about Loading Related Objects
精彩评论