1

I am working with EntityFramework and the IRepository Pattern and I need to add some events to all EntityCollections.

Is there a way to get a list of collections on an ObjectContext?
I also need a way to get all the collections on an ObjectSet/EntityCollection. Is that possible?

My end goal here to iterate all collections and sub-collections and add an AssociationChanged Event to all my sub-collections. It will call delete on an object when the relationship is deleted.

This to make up for the fact that EF does not support connectionless deletes (at least not like it supports connectionless Updates and Inserts).

Community
  • 1
  • 1
Vaccano
  • 78,325
  • 149
  • 468
  • 850

2 Answers2

3

You can get the ObjectSets using the following untested code:

var objSetProps = instanceOfObjectContext.GetType().GetProperties().Where(prop => prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(ObjectSet<>));

foreach(PropertyInfo objSetProp in objSetProps)
{
    var objSet = objSetProp.GetValue(instanceOfObjectContext, BindingFlags.GetProperty, null, null, null);
}

The trick is going to be working with the ObjectSet once you have the instance because it ObjectSet is generic and working with variables of generic types can be less then obvious when you don't know what type was used to define them.

As for getting the entity collections on an object set, a similar approach can be taken, but I don't have an example of doing so on hand at the moment.

M.Babcock
  • 18,753
  • 6
  • 54
  • 84
  • That is good, but in the end it does not work for me because I cannot reference the object as an ObjectSet. (The var equates to an `object`.) And since I don't know the type at compile time (and ObjectSet has to be generic, there is no way to get the list of EntityCollections from that object set. :( – Vaccano Dec 19 '11 at 22:41
2

To extend on the above answer regarding the ObjectSet approach, in my case to establish the underlying type within the generic propertyinfo type you perform the following:

propertyInfo.PropertyType.GetGenericArguments();

Which will give you the types of parameters applied to this particular generic type at runtime. I believe for EntityFramework these ObjectSets only support a single parameter so to find out the underlying object type would simply be:

propertyInfo.PropertyType.GetGenericArguments().First();

Thanks to M. Babcock above who got me here in the first place.

The Senator
  • 5,181
  • 2
  • 34
  • 49