In my MVVM program I have a Model class (say MyModel) from which I have an instance of reading from the database (using Entity Framework). When retrieving the o
I found this looking to see if there was a better way to clone an object than I was currently using and noticed that there is a potential problem with the accepted answer if you are trying to do multiple clones...at least if you want to avoid creating your context many times...
I don't know if this is the best approach to cloning, which is why I was looking for another way. But, it works. If you need to clone an entity multiple times, you can use JSON serialization to clone...something like this (using Newtonsoft JSON).
using( var context = new Context() ) {
Link link = context.Links.Where(x => x.Id == someId);
bool isFirst = true;
foreach( var id in userIds ) {
if( isFirst ) {
link.UserId = id;
isFirst = false;
}
else {
string cloneString = JsonConvert.SerializeObject(link);
Link clone = JsonConvert.DeserializeObject(cloneString);
clone.UserId = id;
context.Links.Add(clone);
}
}
context.SaveChanges();
}