Search code examples
linqentity-frameworkentity-framework-5entity-framework-6linq-to-objects

How to remove inner collection from a collection using LINQ or Entity Framework?


I have an IEnumerable<myObject> myCollection. myObject has the following structure - it contains 2 collections and 2 additional properties like this:

 public virtual ICollection<innerObject> innerObjects{ get; set; }
 public virtual ICollection<innerObject1> innerObjects1 { get; set; }

I have not used 'LazyLoadingEnabled=false' while using Entity Framework as I want the inner collection to be loaded when I fetch from the database.

In this case. I have the inner collection, but I want to empty the inner collection before returning the collection to the calling method.

Please suggest a good approach. Currently I am just thinking of removing the inner collection using LINQ.


Solution

  • Just to clarify, with LazyLoadingEnabled the inner collection will be loaded when first accessed - not when the containing object is fetched from the database. If you want to explicitly fetch the inner collection at the same time as the containing object you will want to use explicit or eager loading of the inner collection.

    If you want Entity Framework to unload the inner collection - i.e. stop tracking it and disconnect it from the containing object, you could do the following:

    myObject.innerObjects.ToList().ForEach(x => x.myContext.Entry(x).State = EntityState.Detached);

    This iterates over the inner collection and tells Entity Framework to stop tracking each of the child items. The child items are also removed from the collection.

    In your case, as you are using lazy loading, any access of the inner child collection will trigger a lazy load of the collection even after the child items have been detached.

    NOTE, it is not possible to remove the child entities from the collection using LINQ without the risk of a future SaveChanges removing the relationship at the data level.

    E.g:

    myObject.innerObjects = null;

    or

    myObject.innerObjects = new List<InnerEntity>();

    would both remove the child entities from the parent at the data level if followed by a SavesChanges().

    If I have understood the question correctly and this is what you are looking to achieve, I would also recommend moving away from lazy loading. I.e. if you are trying to explicitly shape your object graphs you will always be competing against the lazy loading proxies.