Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8693327
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T00:31:27+00:00 2026-06-13T00:31:27+00:00

Relate to : Set Properties that not null using linq and reflection Hi experts

  • 0

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T00:31:28+00:00Added an answer on June 13, 2026 at 12:31 am

    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:

    public static T CloneBySerialization<T>(this T source) where T : EntityObject {
        var serializer = new DataContractSerializer(typeof(T));
        using (var ios = new MemoryStream()) {
            serializer.WriteObject(ios, source);
            ios.Seek(0, SeekOrigin.Begin);
            return ((T) serializer.ReadObject(ios));
        }
    }
    

    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.

    public static void ClearReferences(this EntityObject entity) {
        if (entity == null)
            return;
    
        foreach (var p in entity.GetType().GetProperties()) {
            if (p.PropertyType.IsGenericType) {
    
                var propertyType = p.PropertyType.GetGenericTypeDefinition();
    
                if (propertyType == typeof(EntityReference<>)) {
                    var reference = p.GetValue(entity) as dynamic;
                    if (reference.EntityKey != null) {
                        reference.EntityKey = null;
                        ((EntityObject) reference.Value).ClearReferences();
                    }
                }
    
                if (propertyType == typeof(EntityCollection<>)) {
                    var children = (p.GetValue(entity) as IEnumerable<EntityObject>).ToList(); // covariance
                    foreach (var child in children)
                        child.ClearReferences();
                }
            }
        }
    }
    

    So the idea is that you first clone (via serialization/deserialization), then you “purify”.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This question may not directly relate to programming. I have noticed that the technology
Hia, I got a somewhat odd problem. Im using two managed Classes that relate
I have two related POCOs public class Parent { public Guid Id {get; set;}
I am working with some business objects that relate to one another through their
In the following code example how do the user/userParam references relate to the Customer
I looked at previous post based on this but they do not relate. I
Microsoft web application architecture related... Wondering if I'm making a mistake by not using
I have an ASP.NET MVC application that is using a single view to display
I have a simple question. I have a model that looks like this: public
I do not have code at the moment for explaining my question in the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.