Clone Linq object The error "Object graph for type" TestLinq.PersonAddress "contains loops and cannot be serialized if link tracking is disabled."

I need to clone a string using linq. I found this method:

public static T Clone<T>(this T source) { var dcs = new System.Runtime.Serialization .DataContractSerializer(typeof(T)); using (var ms = new System.IO.MemoryStream()) { dcs.WriteObject(ms, source); ms.Seek(0, System.IO.SeekOrigin.Begin); return (T)dcs.ReadObject(ms); } } 

but when trying to clone a string, for example, db1.Persons.First (). Clone ();

I get this exception: "The object graph for type" TestLinq.PersonAddress "contains loops and cannot be serialized if link tracking is disabled."

Note. My table contains 1 primary key and 1 unique index includes 3 fields

Could you help me
Thanks
Hamida

+6
c # serialization linq-to-sql
source share
2 answers

This problem arises because linq objects have a relationship between parents and children in both directions. For example, if you had an Order class mapped to a table and an OrderItem class mapped to another table, you expect the OrderItem table to look like this:

CREATE TABLE OrderItem (... OrderId int links Order (Id))

The generated linq objects will look like this:

 public class Order { //other members public EntitySet<OrderItem> OrderItems { get; } } public class OrderItem { //other members public Order Order { get; } } 

This cannot be serialized, as there is a circular link between the order and each of them with the names OrderItem. If you use linq2sql desiger to create these classes, you can say that it only creates links in one direction (from parent to child) by clicking on the surface of the constructor and changing "Serialization Mode" to "Unidirectional"

+17
source share

Maybe post the actual class for PersonAddress ? It is interesting, for example, whether you have an association property marked with [DataMember] or not at all [DataMember] ; and in this case it looks at the fields that may occur if you have a lazy loaded item (and therefore an association with the data context).

Please note that if you need only one object (not associations), there are other ways to make a small clone - for example, like this .

0
source share

All Articles