1

I have the fowling models:

public class Order 
{ 
    public int OrderId { get; set; } 
    //
    public virtual ICollection<Client> Clients { get; set; } 
} 

public class Client 
{ 
    public int ClientId { get; set; } 
    public string ClientName { get; set; } 
    public virtual Order Order { get; set; } 
} 

When I use Web Api by generating an EF scaffolding API controller, it didn't work. The error is below:

Self referencing loop detected for property 'Order' with type 
'System.Data.Entity.DynamicProxies.Order_A97AC61AD05BA6A886755C779FD3F96E86FE903ED7C9BA9400E79162C11BA719'. 
Path '[0].Order[0]'

Can anyone help me solve the problem?

1
  • The problem may be the serializer, you need to disable that. Commented Nov 9, 2013 at 21:15

1 Answer 1

3

The serializer can't handle circular references. You can disable it in the data context class:

public YourDbContext() : base("name=YourConnectionString") 
 { 
     Database.SetInitializer(new CircularReferenceDataInitializer()); 
     this.Configuration.LazyLoadingEnabled = false; 
     this.Configuration.ProxyCreationEnabled = false; 
 } 

Like this, the navigation property won't be lazy loaded. If you want to use lazy loading, you can try the following:

1) dealing with circular reference by ignoring it. Add the below code in your WebApiConfig.cs file.

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

2)Preserve circular reference by adding the below code in your WebApiConfig.cs file.

 config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize; 
 config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.