Relate to : Set Properties that not null using linq and reflection
Hi experts
I change the code in above link:
public static void MyCopy<T>(this T src, T dest)
{
var notNullProps = typeof(T).GetProperties()
.Where(x => x.GetValue(src, null) != null);
foreach (var p in notNullProps)
{
p.SetValue(dest, p.GetValue(src, null),null);
}
}
and I wrote this code to copy peroperties:
NorthwindModel1.Order ord1 = new NorthwindModel1.Order() {CustomerID="Nima",Freight=1.33m,ShipCity="Agha" };
NorthwindModel1.Order ord2 = new NorthwindModel1.Order() ;
ord1.MyCopy(ord2);
but I got this error:
The EntityReference has already been initialized. InitializeRelatedReference should only be used to initialize a new EntityReference during deserialization of an entity object.
please help me to solve this problem
As mentioned in the comments, your reflective code is not the problem, but the fact that (as the exception message explicitly tells) you are indirectly triggering a reset of one of your entity references. My advice is twofold: either modify your reflective code to ONLY copy scalar properties (strings, dates, etc..) — alternatively ignore references and collections — OR use serialization:
I must warn you that with this approach you will end up the full object graph or references. If the cloned object is an entity, YOU WILL NOT BE ABLE to use it/attach it to another context, due to the fact that references and foreign keys have been also copied, “verbatim”, and this will all likely result in conflicts. The problem gets worse if you’re using identity columns in keys.
I’ve done a lot of magic in my previous work on these matters, and as far as cloning is concerned, the code above is all you need. All, really.
However, to fix the context issue and the usability of your cloned entity, you will have to clear-off the references and under the assumptions that you’re also working with “root” entities in the ¹ ↔ * directional relational graph (I hope I am remotely clear, because the story is long) the following will also be necessary.
So the idea is that you first clone (via serialization/deserialization), then you “purify”.