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

Topics: Web Api
Nov 17, 2011 at 8:11 PM
Edited Nov 17, 2011 at 8:22 PM

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; 
 
    } 
Nov 17, 2011 at 9:06 PM

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 playlists; 
  }
}

This worked out for me fine.