problem with child object

May 27, 2010 at 5:02 PM

Hi,

I am new and i am tring this library because I have problem with JsonResult of asp net mvc  

when I try to serialize a entities with a child entity with JsonResult   I receive this error:

"A circular reference was detected while serializing an object of type" ... I read on internet that It is a problem  

Someone advise me to try this library but I receive an other error

"System.Reflection.TargetException was unhandled by user code  Message=Object does not match target type.  Source=mscorlib  StackTrace:       at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)       at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)       at Newtonsoft.Json.Serialization.JsonContract.InvokeOnSerializing(Object o, StreamingContext context) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\Serialization\JsonContract.cs:line 111       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IList values, JsonArrayContract contract, JsonProperty member) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 373       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonProperty member, JsonContract contract) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 127       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.WriteMemberInfoProperty(JsonWriter writer, Object memberValue, JsonProperty property, JsonContract contract) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 202       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 326       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonProperty member, JsonContract contract) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 112       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IList values, JsonArrayContract contract, JsonProperty member) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 424       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonProperty member, JsonContract contract) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 127       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IList values, JsonArrayContract contract, JsonProperty member) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 424       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonProperty member, JsonContract contract) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 123       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalWriter.cs:line 65       at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\JsonSerializer.cs:line 451       at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\JsonSerializer.cs:line 443       at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Formatting formatting, JsonSerializerSettings settings) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\JsonConvert.cs:line 582       at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Formatting formatting) in C:\Temp\_jsonnetsrc\Source\Src\Newtonsoft.Json\JsonConvert.cs:line 532       at Esempio.Controllers.SituazioneProdottiController._elencoprodinv() in c:\temp\Esempio\Esempio\Controllers\SituazioneProdottiController.cs:line 44       at lambda_method(Closure , ControllerBase , Object[] )       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)       at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a()       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)  InnerException: 

"

The entities are very easy:

TabA (idA,field AAA)

TabB (idB, field BBB, field ida [ forgein key with TabA ])

my LINQ TO ENTITIES query:

var pr = (from x in model.TabA.Include("TabB") select x);

 

Where is the problem ??

(I use NET 4.0, i compile the source code without error.... is right with solution?)

Thanks 

Davide

 

Coordinator
May 27, 2010 at 10:32 PM

I need the source code of the objects being serialized and class values to be able to figure out what is going on.

May 28, 2010 at 7:48 AM

Hi,

thanks for reply

My code is very easy... is a simple test:

 public ActionResult elencoprodinv()      
 {          

 int limit = Convert.ToInt32(Request["limit"]);          
 int start = Convert.ToInt32(Request["start"]);
 var prod = Rep.ElencoProdInventario(start, limit);   
         string g = JsonConvert.SerializeObject(prod ,Formatting.Indented); 

   }

public IQueryable ElencoProdInventario(int start, int limit)      
 {      

       var pr = (from x in model.TabA.Include("TabB") select x);                      
       return pr;        

 

I post the model of linq entitis for TabA e TabB too ... but there are very easy table for test, for simulate a master-detail ... there are :

TabA (idA,field AAA)  [where idA is KEY]

TabB (idB, field BBB, field ida ) [where idB as key and ida is the forgein key in relation with key idA of TabA]

there are 2 records in TabA and 4 records in TabB

 

LINQ ENTITIES MODEL:
------------------------------ 

/// No Metadata Documentation available.
/// </summary>
[EdmEntityTypeAttribute(NamespaceName="AdventureWorksModel", Name="TabA")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class TabA : EntityObject
{
#region Factory Method

/// <summary>
/// Create a new TabA object.
/// </summary>
/// <param name="idA">Initial value of the idA property.</param>
public static TabA CreateTabA(global::System.Int32 idA)
{
TabA tabA = new TabA();
tabA.idA = idA;
return tabA;
}

#endregion
#region Primitive Properties

/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 idA
{
get
{
return _idA;
}
set
{
if (_idA != value)
{
OnidAChanging(value);
ReportPropertyChanging("idA");
_idA = StructuralObject.SetValidValue(value);
ReportPropertyChanged("idA");
OnidAChanged();
}
}
}
private global::System.Int32 _idA;
partial void OnidAChanging(global::System.Int32 value);
partial void OnidAChanged();

/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String AAA
{
get
{
return _AAA;
}
set
{
OnAAAChanging(value);
ReportPropertyChanging("AAA");
_AAA = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("AAA");
OnAAAChanged();
}
}
private global::System.String _AAA;
partial void OnAAAChanging(global::System.String value);
partial void OnAAAChanged();

#endregion

#region Navigation Properties

/// <summary>
/// No Metadata Documentation available.
/// </summary>
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("AdventureWorksModel", "FK_TabB_TabA", "TabB")]
public EntityCollection<TabB> TabB
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<TabB>("AdventureWorksModel.FK_TabB_TabA", "TabB");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<TabB>("AdventureWorksModel.FK_TabB_TabA", "TabB", value);
}
}
}

#endregion
}

/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmEntityTypeAttribute(NamespaceName="AdventureWorksModel", Name="TabB")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class TabB : EntityObject
{
#region Factory Method

/// <summary>
/// Create a new TabB object.
/// </summary>
/// <param name="idB">Initial value of the idB property.</param>
public static TabB CreateTabB(global::System.Int32 idB)
{
TabB tabB = new TabB();
tabB.idB = idB;
return tabB;
}

#endregion
#region Primitive Properties

/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 idB
{
get
{
return _idB;
}
set
{
if (_idB != value)
{
OnidBChanging(value);
ReportPropertyChanging("idB");
_idB = StructuralObject.SetValidValue(value);
ReportPropertyChanged("idB");
OnidBChanged();
}
}
}
private global::System.Int32 _idB;
partial void OnidBChanging(global::System.Int32 value);
partial void OnidBChanged();

/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String BBB
{
get
{
return _BBB;
}
set
{
OnBBBChanging(value);
ReportPropertyChanging("BBB");
_BBB = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("BBB");
OnBBBChanged();
}
}
private global::System.String _BBB;
partial void OnBBBChanging(global::System.String value);
partial void OnBBBChanged();

#endregion

#region Navigation Properties

/// <summary>
/// No Metadata Documentation available.
/// </summary>
[XmlIgnoreAttribute()][ScriptIgnore()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]


[EdmRelationshipNavigationPropertyAttribute("AdventureWorksModel", "FK_TabB_TabA", "TabA")]
public TabA TabA
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<TabA>("AdventureWorksModel.FK_TabB_TabA", "TabA").Value;
}
set
{
((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<TabA>("AdventureWorksModel.FK_TabB_TabA", "TabA").Value = value;
}
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[BrowsableAttribute(false)]
[DataMemberAttribute()]


public EntityReference<TabA> TabAReference
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<TabA>("AdventureWorksModel.FK_TabB_TabA", "TabA");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<TabA>("AdventureWorksModel.FK_TabB_TabA", "TabA", value);
}
}
}

#endregion
}

Jul 29, 2010 at 8:20 PM
Hi, I had this issue as well with an EntityCollection. I have uploaded a patch today that should fix this details at http://json.codeplex.com/SourceControl/PatchList.aspx patch file is http://json.codeplex.com/Project/Download/FileDownload.aspx?DownloadId=139252 Hope this helps. Cheers Simon
Nov 15, 2010 at 5:56 PM

Simons patch is a must have when working with Entity Framework 4.0.

Please consider this patch for the next release.

Thanks

Coordinator
Nov 18, 2010 at 5:52 AM

I've already updated the main project to .NET 4 and I haven't gotten this error from the Entity Framework tests.

Do you have a snippet of code that reproduces the problem? I don't want to make changes unless I can see the error for myself and throw it into a unit test.

Nov 18, 2010 at 7:28 AM

Hi,

I remember that I have solve my problem with use .ToList of my object with Include the child object

first:

var pr = (from x in model.TabA.Include("TabB") select x);

now:

var pr = (from x in model.TabA.Include("TabB") select x).ToList();

It is no good solution but work

 

Nov 18, 2010 at 6:58 PM

JamesNK, I am sorry but I unable right now to give you a repo but in essence the problem arises when the EF generated entity objects are in a seperate DLL from the DLL doing the serialization.

cdavide75, ToList() forces the query to IEnumerable and therefore starts to execute locally. In my case, I would like my API as IQueryable as I need to add additional expressions before executing the query. In my case, there can be a considerable performance hit making the query execute locally. Also, in my case I am passing the query to another third party library which would have to be modified to do a ToList() before serializing and this is actually the crux of my problem. IMHO, I think that this is a problem best resolved in the Json serializer as I suspect that people running into this problem are just resorting to doing a ToList().

Many thanks James for the fine work you have done on this project!