Print Page | Close Window

Data Reflection

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2010
Forum Discription: For .NET 4.0
Printed Date: 22-May-2022 at 8:15pm

Topic: Data Reflection
Posted By: BillG
Subject: Data Reflection
Date Posted: 24-Jan-2014 at 3:36pm
I have a situation where i have an called job which is an instance of the class JobHistory. I need to pass a job object to a method called BuildNewJobFromExistingJob(). In the method, I need to create a new job object. Then i need to copy all the data from the old object to the new object. Finally i need to change a few of the fields in the object.

I am thinking of the following as a solution.

var job = Repository.CreateJobHistory()

then i want to loop through all the fields of the old object to the new object. I don't want to hard code the copying of the data as fields may be added in the future.

How do i loop through all the fields in and object copying the data from one to a new object of the same type?


Posted By: DenisK
Date Posted: 27-Jan-2014 at 1:54pm
Hi Bill,

One way to do this is through the use of the entity metadata. 

Below is a code snippet:

//Grab an entity metadata using its type
var entityMetadata = entityManager.MetadataStore.GetEntityMetadata(typeof(YourEntity));

//Loop through the data properties of the entity
foreach (var dataProperty in entityMetadata.DataProperties) {
//Cloning logic here

Hope this helps.

Posted By: BillG
Date Posted: 27-Jan-2014 at 5:12pm
so this is what i have so far then

           var query = _manager.JobHistories
                .Where(j => j.RefNo == refNo);
           var oldJob = query.Execute().FirstOrDefault();
           var newJob = _manager.CreateEntity<JobHistory>();
           var entityMetadata = _manager.MetadataStore.GetEntityMetadata(typeof(JobHistory));
            foreach (var dataProperty in entityMetadata.DataProperties)

so now i need to copy the property values from oldJob to newJob

Posted By: DenisK
Date Posted: 28-Jan-2014 at 6:12pm
That's correct. You can use the following logic to copy values from oldJob to newJob

var valueToCopy = dataProperty.GetValue(oldJob);
dataProperty.SetValue(newJob, valueToCopy);

Print Page | Close Window