Here is what I have so far, and it seems to work pretty good. I am going to extend this to specify what properties that hold child entities to copy.
ManagerBase
Region "Clone"
Protected Shared Function GenericCloneObject(ByVal obj As Object) As Object
'Create a memory stream
Dim ms As New MemoryStream
Dim bf As New BinaryFormatter(Nothing, New StreamingContext(StreamingContextStates.Clone))
'serialize object into the stream
bf.Serialize(ms, obj)
'position stream pointer back to first byte
ms.Seek(0, SeekOrigin.Begin)
'deserilize into another object
GenericCloneObject = CType(bf.Deserialize(ms), IEntity2)
'Release memory
ms.Close()
End Function
#End Region
QueryManagerBase : Inehrits ManagerBase
#Region "Clone & Copy "
Public Shared Function CloneObject(ByVal obj As QueryEntity) As QueryEntity
Return CType(GenericCloneObject(obj),QueryEntity)
End Function
Public Shared Function CopyObject(ByVal entityToCopy As QueryEntity) As QueryEntity
Dim copiedEntity As QueryEntity = CloneObject(entityToCopy)
ResetFieldsInCopy(copiedEntity)
'now reset fields in all needed childentities
Dim memberEntities As ArrayList = copiedEntity.GetMemberEntityCollections()
For Each coll As EntityCollectionBase2 In memberEntities
For Each subEntity As IEntity2 In coll
ResetFieldsInCopy(subEntity)
Next
Next
Return copiedEntity
End Function
Private Shared Sub ResetFieldsInCopy(ByVal copiedEntity As IEntity2)
copiedEntity.IsNew = True
Dim fields As IEntityFields2 = copiedEntity.Fields
For i As Integer = 0 To fields.Count - 1
fields(i).IsChanged = True
Next
fields.IsDirty = True
End Sub
#End Region