Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone Linq object Error "Object graph for type 'TestLinq.PersonAddress' contains cycles and cannot be serialized if reference tracking is disabled."

I Need to clone row 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 try to clone row, like db1.Persons.First().Clone();

i get this exception: "Object graph for type 'TestLinq.PersonAddress' contains cycles and cannot be serialized if reference tracking is disabled."

Note: My Table contains 1 primary key and 1 unique index include 3 field

Could you please help me
Thanks
Hamid

like image 423
Hamid Avatar asked Sep 16 '09 11:09

Hamid


1 Answers

This problem occurs because linq entities tend to have links between parents and children items in both directions. For example, if you had an Order class mapped to a table, and an OrderItem class mapped to another table, you would expect the OrderItem table to look like this:

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

The generated linq entities would then 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 serialised since there is a circular reference between an order and each of it's OrderItem children. If you're using the linq2sql desiger to create these classes you can tell it to only create references in one direction (from parent to child) by clicking on the designer surface and changing 'Serialization Mode' to 'Unidirectional'

like image 149
Lee Avatar answered Oct 02 '22 20:10

Lee