使用泛型复制实体的一种非常短的方法(VB,抱歉)。
它复制外键值(外部 ID)但不加载它们的相关对象。
<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
例如:
newDad = ctx.DuplicateEntity(oDad)
newDad.RIDGrandpa ' int value copied
newDad.Grandpa ' object for RIDGrandpa above, equals Nothing(null)
newDad.Children ' nothing, empty
在这种情况下,我不知道如何重新加载 Grandpa。
这不起作用:
ctx.SaveChanges()
ctx.Entry(newDad).Reload()
但实际上,没问题。如果需要,我宁愿手动分配Grandpa。
newDad.Grandpa = oDad.Grandpa
编辑:
作为MattW proposes in his comment,分离并找到新实体,您会加载它的子实体(而不是集合)。
ctx.Entry(newDad).State = EntityState.Detached
ctx.Find(newDad.RowId) 'you have to know the key name