Search code examples
c#entity-frameworkdetach

Why does EF remove child entities when detaching?


I need to do something like ...

  1. get a db context (UtilitiesContext)
  2. query it for some data (Watched Directories)
  3. Also pull children from the db when i pull the WD's (AdditionalData)
  4. Dispose of context
  5. Continue to use entities

...

// step 1
using (var db = new UtilitiesContext(false))
{
    var jsonSettings = new JsonSerializerSettings { MaxDepth = 2, ReferenceLoopHandling = ReferenceLoopHandling.Ignore };

    // step 2
    var dirs = db.GetAll<WatchedDirectory>();

    // step 3 (lazy load and serialize the WD and its additional data)
    log.Debug(JsonConvert.SerializeObject(dirs, jsonSettings));

    foreach (var d in dirs)
    {
        try
        {
            log.Debug("    Initialising monitoring for path " + d.UNCPath);

            // detach the object and its data items from the db
            db.Detach(d);
            d.AdditionalData.ForEach(i => db.Detach(i));

            // here the AdditionalData property serialises an empty array
            log.Debug(JsonConvert.SerializeObject(d, jsonSettings));

// step 4 happens down here

My problem is that I get all the data I want in the first log output (line labelled step 3) And then later when I repeat that the child collection is gone and all I did was detach the entities from the context.

My detach method looks like this ...

public void Detach(object entity)
{
    Entry(entity).State = EntityState.Detached;
}

Solution

  • EF is a funny beast, this is ultimate cure for detaching an entity from a context ...

    var jsonSettings = new JsonSerializerSettings { MaxDepth = 2, ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
    var dirs = JsonConvert.DeserializeObject<List<WatchedDirectory>>(JsonConvert.SerializeObject(db.GetAll<WatchedDirectory>().ToList(), jsonSettings));
    

    There are probably better practices for this but this bull in china shop approach solved my issue.