views:

673

answers:

2

Hi to all

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

A: 

Maybe post the actual class for PersonAddress? I wonder, for example, whether you have either an association property marked [DataMember], or no [DataMember]s at all; in which case it looks at fields - which might bork if you have a lazy-loaded member (and thus an association to the data-context).

Note that if you only want the one object (not associations), there are other ways of doing a shallow clone - like so, for example.

Marc Gravell
+4  A: 

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'

Lee
+1 Great! needed that :)
magnus
another +1, it helped a bunch!!
Kevin