我正在将审核添加到我的EF4(模型优先)应用程序中。我可以获得有关更改的实体的结构属性的详细信息。我还可以看到多对多关系何时发生变化。我可以看到涉及的类型的名称和发生的事情(添加或删除),但我真正喜欢的是关系变化中涉及的实体的Id。
以下是我目前用于跟踪多对多关系变更的内容:
var changes = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified);
var auditTime = DateTime.Now;
foreach (var change in changes)
{
if (change.Entity != null && change.Entity.GetType().Equals(typeof(AuditTrail)))
{
continue;
}
var detailsBuilder = new StringBuilder();
if (change.Entity == null & (change.State == EntityState.Added | change.State == EntityState.Deleted))
{
detailsBuilder.Append("A link between entities ");
foreach (var changedMember in change.EntitySet.ElementType.KeyMembers)
{
detailsBuilder.AppendFormat("{0}", changedMember.Name);
if(change.EntitySet.ElementType.KeyMembers.IndexOf(changedMember) < change.EntitySet.ElementType.KeyMembers.Count -2)
{
detailsBuilder.Append(", ");
}
else if (change.EntitySet.ElementType.KeyMembers.IndexOf(changedMember) == change.EntitySet.ElementType.KeyMembers.Count - 2)
{
detailsBuilder.Append(" and ");
}
}
detailsBuilder.AppendFormat(" was {0}.<br />", change.State);
}
}
如何获得关系变化中涉及的细节(甚至实际实体)?
更新
经过几个小时的探索后,我找到了所需的信息(见附图)。但是,存储数据的类是内部密封类,我找不到公共条目来查询对象状态管理器以获取此信息。所以我可以审核这个变化。
答案 0 :(得分:1)
这可能会帮助你:
IEnumerable<IRelatedEnd> relatedEnds = ((IEntityWithRelationships) change.Entity).RelationshipManager.GetAllRelatedEnds();
foreach (var relatedEnd in relatedEnds)
{
foreach (var subEntity in relatedEnd)
{
if (subEntity is IEntityWithRelationships)
{
var entityAssociated = (IEntityWithRelationships)subEntity;
// Now you have your associated entity to work with...
}
}
}
答案 1 :(得分:0)
您可以通过RelationshipEntry的CurrentValues属性访问两个EntityKey对象(派生自ObjectStateEntry)。应该给你你需要的东西。