Serialize Parent / Child with EF and WebApi

I have the following model inside an entity framework:

public class Customer
{
[XmlIgnore]
public virtual ICollection<Customer> Children { get; set; }

public string Name { get; set; }
}

Now I am trying to serialize this using the web api:

public class CustomerController:ApiController {
   public HttpResponseMessage GetAll()
   {
     using (var tc = new DataContext())
     {
        List<Customer> allCustomers = tc.Customers.ToList();
        return Request.CreateResponse(HttpStatusCode.OK, allCustomers);              
     }
   }
}

When I do this and get called by the POST method, I get the following error:

Object type ObjectContent`1 could not serialize the response body for the content type 'application / json; encoding = UTF-8

InnerException: "Error getting value from 'Children' on 'System.Data.Entity.DynamicProxies.Customer"

InnerException (2): "The ObjectContext has been deleted and can no longer be used for operations that require a connection."

clients.Children is currently an empty list.

, , , , " ". ( , )

XmlIgnore, , .

+4
2

virtual Lazy Loading. -, virtual . , XML-, :

public class YourContext : DbContext 
{ 
    public YourContext() 
    { 
        this.Configuration.LazyLoadingEnabled = false; 
    } 
}

(Children), Include . .

using System.Data.Entity;  // For extension method `Include`

List<Customer> allCustomers = tc.Customers.Include(c=>c.Children).ToList();

, :

virtual , POCO , , EF - . , virtual, . . , .

+4

: :

public class Customer
{
[XmlIgnore,JSonIgnore]
public virtual ICollection<Customer> Children { get; set; }

public string Name { get; set; }
}

- "JsonIgnore".

: @octavioccl - , , .

+1

Source: https://habr.com/ru/post/1589223/


All Articles