A very short way to duplicate objects using generics (VB, sorry).
It copies foreign key values ββ(external identifiers), but does not load related objects.
<Extension> _ Public Function DuplicateEntity(Of T As {New, Class})(ctx As myContext, ent As T) As T Dim other As New T 'T is a proxy type, but New T creates a non proxy instance ctx.Entry(other).State = EntityState.Added 'attaches it to ctx ctx.Entry(other).CurrentValues.SetValues(ent) 'copies primitive properties Return other End Function
For example:
newDad = ctx.DuplicateEntity(oDad) newDad.RIDGrandpa ' int value copied newDad.Grandpa ' object for RIDGrandpa above, equals Nothing(null) newDad.Children ' nothing, empty
I donβt know exactly how to restart Grandpa in this case.
This does not work:
ctx.SaveChanges() ctx.Entry(newDad).Reload()
but really, no problem. I would prefer to assign Grandpa manually if I need it.
newDad.Grandpa = oDad.Grandpa
EDIT: As MattW suggests in your commentary , separating and discovering a new object, you load its children (not collections).
ctx.Entry(newDad).State = EntityState.Detached ctx.Find(newDad.RowId) 'you have to know the key name
Ivan Ferrer Villa Jan 25 '16 at 21:47 2016-01-25 21:47
source share