Matt Connolly
Matt Connolly

Reputation: 1233

Entity Framework 4 Problem Saving Clone of Entity with Lookup Reference

I have a method where I am trying to create a duplicate of an Address object. Address has a foreign key reference to StateProvince.

// ... get address from context
var newAddress = Util.DataContractSerialization<Address>(sourceAddress); // serializes and deserializes into/from memory
newAddress.AddressId = Guid.Empty;
ctx.Attach(newAddress); // error!

How should I be doing this? The reason this errors is because the StateProvince property is already in the context when I call Attach, which tries to Attach the entire object graph. My current workaround is a helper method that explicitly copies the StateProvinceId but not the StateProvince object.

I would imagine this error could occur in other situations, so I want to figure out the right way to solve this problem.

Upvotes: 3

Views: 362

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364409

Yes that is because serialization makes deep clone of the whole object graph. You don't want deep clone when you need to clone only top level object. I'm usually doing this by implementing ICloneable on entities and clonning manually just entity without its relations. There is no better way except manullay marking all navigation properties as not serializable (IgnoreDataMemberAttribute or not marking as DataMember in case of data contract serialization).

Upvotes: 2

Related Questions