Deleting a parent entity and related child entities with RIA Services

September 22, 2011 at 12:31 AMdsoltesz

I created an extension that will allow you to traverse child entities easily so that you can remove each one from the parent.  Code is below.

 

public static class EntityExtensions { #region Static Methods (public) public static IEnumerable TraverseChildEntities ( this Entity parent, EntityContainer container ) { IEnumerable entityCollectionProperties = from p in parent.GetType( ).GetProperties( ) where p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition( ) == typeof ( EntityCollection<> ) select p; //// For every entity list, bind to the entity removed event foreach ( PropertyInfo property in entityCollectionProperties ) { var collectionType = property.PropertyType.GetGenericArguments()[0]; EntitySet set; if (!container.TryGetEntitySet(collectionType,out set)) { continue; } var entityCollection = ( IEnumerable )property.GetValue( parent, null ); foreach ( Entity entity in entityCollection ) { foreach ( Entity childEntity in entity.TraverseChildEntities(container ) ) { yield return childEntity; } yield return entity; } } } #endregion }

 With this extension in place now when I want to delete a parent entity and related child entities I can do somethig like this.

 

foreach (var child in new List(Parent.TraverseChildEntities(DomainContext.EntityContainer))) { DomainContext.EntityContainer.GetEntitySet(child.GetType()).Remove(child); } DomainContext.Parents.Remove(parent);

Posted in: c# | silverlight | wcf ria services

Tags: , ,

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading