Join For Free New whitepaper: Discover 6 tips for continuous delivery with Database DevOps in this new whitepaper from Redgate. In 9 pages, it covers version control for databases and configurations, branching and testing, automation, using NuGet packages, and advice for how to start a pioneering Database DevOps project. Also includes further research on the industry-wide state of Database DevOps, how application and database development compare, plus practical steps for bringing DevOps to your database.
Read it now free. The Approach This morning I put together a simple data model with the relationships that I wanted to support with detached entities. Theoretically, if I can handle the entity types in a generic fashion, then this solution can scale out to larger and more complex models. Unfortunately the best place for change tracking to occur with disconnected entities is with the layer making changes — be it a business layer or something downstream.
To this effect, entities will need to implement a property which reflects the state of the entity added, modified, deleted etc. Establishing some Scaffolding After generating the data model, the first thing to be done is ensure each entity derives from the same base class. As with my ongoing project, the Entity Framework DbContext is instantiated by this class on construction, and implements IDisposable to ensure the DbContext is disposed properly upon construction.
Updating a Many-to-Many Relationship Now things get interesting. This is mainly in case we need to reuse the logic, since it essentially processes state action on attached entities. Attach item ; if item. Corresponding Unit Test The following unit test establishes the creation of a new many-to-many entity, it is then removed by relationship and then finally deleted altogether from the database: The one bug catch is that you need to specify the navigation property or collection, which might make it slightly undesirable to implement generically.
Attach child ; obj. ChangeRelationshipState parent, child, expression, EntityState. We need this level of access to get to the functionality which controls relationships. For each child to be removed note: Entry attachedEntity ; attachedEntry. Summary This article is the culmination of about two days of heavy analysis and investigation. To be honest, I was quite excited by the initial results, which is why I decided to write this post.
In the meantime though, if any of this helps anyone out there struggling with detached entities, I hope it helps. This is provided without any warranty of any kind!