2011-06-08 129 views
0

是否可以在不知道類型的情況下獲取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. 

我想知道如果也許我正在接近這worng的方式。

+0

當你說「父母」時,我假設你的意思是「孩子」實體與另一個實體處於一對多關係,並且處於許多末端。所以你想知道在一端的類型?我理解正確嗎? – CodingGorilla 2011-06-08 15:24:34

+0

你說得對。我想知道類型名稱和主鍵,所以我可以記錄更改,「ID爲'1222'的名爲'Spot'的狗在ID爲'12313'的Canine上更改了。 – Carlosfocker 2011-06-08 15:28:32

+0

您是如何創建實體的,POCO,T4 ,由設計師? – CodingGorilla 2011-06-08 15:42:34

回答

0

搜索後,用EF來做我想要的是不可行的。爲了審計目的,我想抓取繼承樹。我最終創建了一個記錄審計消息的Auditor界面。我爲我想審計的每個EF實體類型創建了Auditor實現。當調用代碼要求實現Auditor接口的類時,我使用來自Microsoft Unity的命名映射來注入具體類,或者如果未找到映射,請避免審覈。