This thread looks to be a little on the old side and therefore may no longer be relevant. Please see if there is a newer thread on the subject and ensure you're using the most recent build of any software if your question regards a particular product.
This thread has been locked and is no longer accepting new posts, if you have a question regarding this topic please email us at support@mindscape.co.nz
|
Hi Do you have any examples of copy or clone type code? Tried to implement my own 'clone' code using deserialisation, however its not happy:
ActivityResponseConsumerMobile arcmDb = uow.ActivityResponseConsumerMobiles.Single(m => m.Id == id); ActivityResponseConsumerMobile arcmNew = new ActivityResponseConsumerMobile();
arcmNew = ObjectClone.Clone<ActivityResponseConsumerMobile>(arcmDb); cloner:
public static T Clone<T>(T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); }
// Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); }
IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); using (stream) { formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } }
getting a null reference on return (T)formatter.Deserialize(stream); is this due to timing? ie the object hasn't been enumerated yet? Regards Dave |
|
|
We use Automapper for deep copying. |
|
|
Thanks Josh01. I've been meaning to have a look at AutoMapper for a while. I wonder if there is a simpler way? Cheers Dave |
|
|
AutoMapper worked for me. I just needed a simple object clone, and not a deepclone. Here is my code:
ActivityResponseConsumerMobile arcmDb = uow.ActivityResponseConsumerMobiles.Single(m => m.Id == id); ActivityResponseConsumerMobile arcmNew = new ActivityResponseConsumerMobile(); Mapper.CreateMap<ActivityResponseConsumerMobile, ActivityResponseConsumerMobile>() .ForMember(dest => dest.EntityState, opt => opt.Ignore()); arcmNew = Mapper.Map<ActivityResponseConsumerMobile, ActivityResponseConsumerMobile>(arcmDb); arcmNew.Name = arcmDb.Name + "_cloned"; uow.Add(arcmNew); uow.SaveChanges(); |
|