dimanche 29 mai 2016

Entity framework get related entites on SavingChanges

I need to get related entites while EF modify relations. I hook SavingChanges event of ObjectContext and getting an entry:

foreach (var entry in
                context.ObjectStateManager.
                    GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted)
                    .Where(x => x.IsRelationship))
{
    var key0Prop = entry.GetType().GetProperty("Key0", 
        BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic);
    var key0 = ObjectContext.GetObjectByKey((EntityKey)key0Prop.GetValue(entry));
    var key1Prop = entry.GetType().GetProperty("Key1",
        BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic);
    var key1 = ObjectContext.GetObjectByKey((EntityKey)key1Prop.GetValue(entry));
}

The entry is internal RelationshipEntry class and I found only way - reflection. I understand this is probably unstable solution. Mybe where exist non reflection method to get related entities object while SavingChanges? Thanks.





Aucun commentaire:

Enregistrer un commentaire