Circular reference, NHibernate and WCF
This problem has been happening over the net for years, I haven't found a good solution yet. A topic is a List of objects that have a circular reference inside them filled with NHibernate (with or without lazy loading - some sites cannot be made lazy)
Here's an example:
[DataContract]
class Person
{
[DataMemeber]
string Name
[DateMember]
IList<Child> myChilds;
}
[DataContract]
class Child
{
[DataMemeber]
string Name
[DateMember]
Person Father
}
When I try to get all the Faces in my DB: The server code will be:
ICriteria crit = session.CreateCriteria(typeof(Person)));
IList<Base> queryResult = crit.List<Base>();
I get good results on the SERVER SIDE - List of all people and inside each person I get a List of all sons (and inside each son - I get a Person object, inside which there is a List of his sons ect ....)
Now, trying to get this list over WCF, it breaks the channel. (if I remove the Person object from the child - it works fine).
The solutions I tried and didn't solve this problem: adding IsReference = true to [DataContract] didn't help. Moving the entire display to not.Lazyload () - didn't help.
Any ideas how to solve this problem without rewriting WCF?
Thanks, Dani
source to share
http://www.jameskovacs.com/blog/CommentView.aspx?guid=477b077c-e65e-4547-8289-4e1bc17b3de7
This article solves the problem.
EDIT:
The link appears to have been dead for a long time. Use the Wayback Machine to view it in an archived version: http://web.archive.org/web/20070219214621/http://www.jameskovacs.com/blog/CommentView.aspx?guid=477b077c-e65e-4547-8289 -4e1bc17b3de7
source to share
IsReference is indeed the official answer here if you want to actually preserve the shape of the object graph. See http://msdn.microsoft.com/en-us/library/cc656708.aspx . Can you talk about what you mean when you say "it didn't help"? Where exactly did you put IsReference? Both client side and server side? What mistakes have you observed?
If you don't care about storing the ref, there are many solutions around breaking an infinite reference loop. The simplest is to remove the DataMember attribute from Father. Or something with a "shadow property":
public Person Father;
[DataMember] public string FatherName
{ get {return Father.Name;} set {/* ... */ }}
It really depends a lot on your exact requirements ...
source to share