I was working with LINQ to SQL classes and was having problem when WCF was returning a List<T> but was returning "A circular reference was detected while serializing an object of type T". This was frustrating as everything seems fine and there was no problem in C# code.
But when i researched i found that LINQ generated classes have many other attributes and also if there are any relational tables the dependencies would be there for the classes which may have reference for child table classes which may cause circular reference. I searched a lot and found that JSON.NET (open source) solves the problem. I downloaded JSON.NET from http://json.codeplex.com/releases/.(Please note that in .NET 4.5 JSON.NET comes in built) and the problem was solved. Here is the code in WCF operationcontract
public string GetEmployees()
{
using(EmployeeDbContext context=new EmployeeDbContext())
{
List<Employee> list=new List<Employee>();
list=(from p in context where p.Salary>=10000 select p).ToList();
string jsonstring=JsonConvert.SerializeObject(list,Formatting.Indented,
new JsonSerializerSettings {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
}
}
To reverse the code would be Employee mylist=JsonConvert.DeserializeObject<Employee>(list);
Thanks
Ritesh
No comments:
Post a Comment
Comments are welcome, Please join me on my Linked In account
http://in.linkedin.com/pub/ritesh-tandon/21/644/33b