【发布时间】:2014-09-26 15:28:53
【问题描述】:
出于审计系统的目的,我需要能够在保存实体之前通过 ChangeTracker/ObjectStateManager 检索实体的导航属性。检索到导航属性后,我将遍历每个属性并保存其名称、类型和主键。
我正在使用以下代码来做到这一点:
var context = new SomeDbContext();
var entity = context.SomeEntities.Find(1);
entity.MakeSomeChanges();
entity.MakeMoreChanges();
context.ObjectContext.DetectChanges();
var stateManager = context.ObjectContext.ObjectStateManager;
var stateEntry = stateManager.GetObjectStateEntry(entity);
var entityType = stateEntry.EntitySet.ElementType as EntityType;
// from here I can work with the navigation properties.
foreach (var property in entityType.NavigationProperties)
{
// process nav property
}
这种方法对基本实体非常有效,但是我遇到的问题是试图在从基本实体继承的实体上找到导航属性。例如,给定以下结构:
public class ParentEntity
{
public int Id { get; set; }
}
public class ChildEntity : ParentEntity
{
public int NavigationEntityId { get; set; }
public virtual NavigationEntity NavigationEntity { get; set; }
}
public class NavigationEntity
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ChildEntity> ChildEntities { get; set; }
}
如何在 ChildEntity 上找到导航属性?如果我使用与 SomeEntity 相同的方法,会发生这种情况:
var context = new SomeDbContext();
var navEntity = context.NavigationEntities.Find(1);
var childEntity = new ChildEntity();
navEntity.ChildEntities.Add(childEntity);
context.ObjectContext.DetectChanges();
var stateManager = context.ObjectContext.ObjectStateManager;
var stateEntry = stateManager.GetObjectStateEntry(childEntity);
// entityType here turns into ParentEntity, which does not have nav properties
var entityType = stateEntry.EntitySet.ElementType as EntityType;
var properties = entityType.NavigationProperties;
// properties.Count() == 0
有什么方法可以将 ParentEntity 转换为 ChildEntity 吗? 或者也许我可以采用不同的方法来检索更改跟踪器中实体的导航属性?
【问题讨论】:
-
entityType.DeclaredNavigationProperties值得调查吗?看不到它们是什么或如何使用它们,因此可能对您没有用。 -
也许,我会试一试。编辑:不幸的是,它没有用,因为 entityType 仍然是 ParentEntity 并且 Edm 认为它没有任何声明的导航属性。 @Rhumborl
标签: c# .net entity-framework entity-framework-6