Find Parent EntityKey and Type in Entity Framework
Is it possible to get the EntityKey and type of an entity's parent entity without knowing the type? I've tried doing the following
public partial class TestEntities
{
partial void OnContextCreated()
{
this.SavingChanges += new EventHandler(logChanges);
}
void logChanges(object sender, EventArgs e)
{
IEnumerable<Obje开发者_如何学GoctStateEntry> changes = this.ObjectStateManager.GetObjectStateEntries(
EntityState.Added |
EntityState.Deleted |
EntityState.Modified);
TestEntities context = sender as TestEntities;
foreach (ObjectStateEntry stateEntryEntity in changes)
{
if (!stateEntryEntity.IsRelationship && stateEntryEntity.Entity != null)
{
Audit audit = new Audit
{
AuditID = Guid.NewGuid()
};
foreach (var relationship in stateEntryEntity.RelationshipManager.GetAllRelatedEnds())
{
var parent = stateEntryEntity.RelationshipManager.GetRelatedCollection<EntityObject>(relationship.RelationshipName, relationship.TargetRoleName);
audit.Decription =
string.Format("{0} changed on {1} with id of {2}",stateEntryEntity.Entity, parent.GetType().Name);
}
context.AddToAudits(audit);
}
}
}
}
But I get the following.
An EntityCollection of EntityObject objects could not be returned for role name
'Canine' in relationship 'TestModel.FK_CANINE'. Make sure that the
EdmRelationshipAttribute that defines this relationship has the correct
RelationshipMultiplicity for this role name. For more information, see the
Entity Framework documentation.
I'm wondering if maybe I'm approaching this the worng way.
After search it isn't feasible to do what I wanted with EF. I wanted to crawl the inheritance tree for Auditing purposes. I ended up creating an Auditor interface that logs an audit message. I created Auditor implementations for the each EF entity type I wanted to audit. When the calling code asked for a class that implemented the Auditor interface I used named mappings from Microsoft Unity to inject the concrete class or avoid auditing if no mapping was found.
精彩评论