Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi with EF Code First generates error when having parent child relation

I am breaking my head over this issue. I did find something on the internet about it, but not a clear answer. My problem:

I have to classes in Model section of an MVC3 web app: ParentClass and ChildClass On ParentClass there is a property Children of type List

I used EF Code First, which neatly generates a parent table and a child table for me in the database.

Now I need a REST service that gives back a List or a single ParentClass.

When I remove the property Children from the ParentClass there is no problem. But with the propoerty Children there I keep getting an error.

Error: "The type System.Data.Entity.DynamicProxies.ParentClass_A0EBE0D1022D01EB84B81873D49DEECC60879FC4152BB115215C3EC16FB8003A was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."}

Some code:

Classes:

     public class ParentClass
{
    public int ID { get; set; }
    public string Name {get;set;}
    public virtual List<ChildrenClass> Children { get; set; }

}

public class ChildrenClass
{
    public int ID { get; set; }
    public string MyProperty { get; set; }
}

Service:

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)] 
public class MyService
{

    static MyContext db;
    public MyService() { db = new MyContext(); }


    [WebGet(UriTemplate = "")]
    public List<ParentClass> GetParents()
    {
        var result = db.Parents.ToList();
        return result;

    }

I will not get the result when callinh this service. What am I doing wrong?

like image 671
Mounhim Avatar asked Nov 17 '11 20:11

Mounhim


1 Answers

I had to DisableProxyCreation in the context configuration:

[OperationContract] 
[WebGet(UriTemplate = "")] 
public List<ParentClass> GetParents() 
{ 
     using (DBContext context = new DBContext()) 
     {
         context.Configuration.ProxyCreationEnabled = false; 
         List<ParentClass> parents = context.Parents
             .Include("Children") 
             .ToList();
         return parents; 
      }
}

This worked out for me fine.

like image 128
Mounhim Avatar answered Nov 06 '22 05:11

Mounhim