How to Get Full Object with Code First Entity Framework 4.1

心已入冬 提交于 2019-12-10 16:55:43

问题


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 Approver { 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.


回答1:


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.




回答2:


Read about Loading Related Objects



来源:https://stackoverflow.com/questions/5585359/how-to-get-full-object-with-code-first-entity-framework-4-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!