Click here to Skip to main content
15,117,095 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a frontend that sends a model to a API which I catch with a endpoint in a controller, lets call this the updated model. I then use the id send with the model to get the original model from the db using a Repo. My questions is, is there a way to iterate through each variable (using a loop) in the model in order for me to assign the updated model info to the original model in order to do a DBContext.SaveChanges().

What I have tried:

What works is:
C#
originalModel.name = updatedModel.name;
And also
C#
originalModel.Settings.maxVolt = updatedModel.Settings.maxVolt;
.
What does not work is:
C#
originalModel = updatedModel;
Posted
Updated 3-Oct-21 21:40pm

I expect you'll need to write a Model.SetFrom(Model src) method to perform a deep copy.  Also see MemberwiseClone()[^].  Simply copying a reference doesn't perform a deep copy.

Remember, MemberwiseClone() performs a shallow copy of each member.

/ravi
   
v2
At the end of the day I just used
C#
dbContext.Update(T entity)
in the Repo, passing the updated model. Since the updated model and the original model have the same id, entity framework could track it. Then after the update I did a save the db.
C#
dbContext.SaveChanges();
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900