是否有可能在不知道类型的情况下获取实体的父实体的EntityKey和类型?我尝试过以下
public partial class TestEntities
{
partial void OnContextCreated()
{
this.SavingChanges += new EventHandler(logChanges);
}
void logChanges(object sender, EventArgs e)
{
IEnumerable<ObjectStateEntry> 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);
}
}
}
}
但我得到以下内容。
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.
我想知道我是否正在接近这种方式。
答案 0 :(得分:0)
搜索后,用EF做我想做的事是不可行的。我想抓取继承树以进行审计。我最终创建了一个记录审计消息的Auditor接口。我为我想要审计的每个EF实体类型创建了Auditor实现。当调用代码要求实现Auditor接口的类时,我使用来自Microsoft Unity的命名映射来注入具体类,或者如果没有找到映射则避免审计。