locked
How do I create an unattached "copy" of an attached entity? RRS feed

  • General discussion

  • WHAT I HAVE:

    Visual Basic 2015, Entity Framework 6.1.3 (dbContext)

    MY PROBLEM:

    Suppose I obtain an "attached" instance of an entity--say, thru a query. Then I want to create another instance which has the same property-values (including, if possible, navigation properties) but is UNattached. How does one do this? I have 2 ideas of how one might do this. Which, if either, will work--and if neither, then what will?

    Hypothetical approach #1:

    Dim AttachedEntity = result from query
    Dim UnattachedEntity = AttachedEntity
    db.Entry(UnattachedEntity).State = Detached 'detach UnattachedEntity

    Hypothetical approach #2:

    Dim AttachedEntity = result from query
    Dim UnattachedEntity = AttachedEntity.MemberwiseClone 'is this copy deep enough for navigation properties?

    After the "copy"--however it's done--I want AttachedEntity to still be attached, but UnattachedEntity to be UNattached, but with the same property-values. (NOTE that I am NOT asking how to create a "stub entity" and attach it. I already know how to do that.)



    Robert Gustafson




    Thursday, February 23, 2017 8:07 AM

All replies

  • I think I've got the solution:

    Dim AttachedEntity As EntityType = result from query

    Dim UnattachedEntity As EntityType = _

    DirectCast(context.Entry(AttachedEntity).CurrentValues.ToObject(), EntityType)


    I just discovered this simple solution by accident in a book!


    Robert Gustafson



    Friday, April 7, 2017 2:05 AM