2011-04-04 77 views
1

我有一個實體框架CodeFirst類(POCO)客戶端:使用接口/抽象類與實體框架CodeFirst

void context_SavingChanges(object sender, EventArgs e) 
{ 

    foreach (ObjectStateEntry entry in 
     ((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(
     EntityState.Added | EntityState.Modified | EntityState.Deleted)) 
    { 

     IMyContract myContract = entry.Entity as IMyContract; 
     if(myContract != null) 
     { 
      ... 
     } 
    } 
} 

回答

3

你提到的代碼第一,但在同一時間,你正在處理的ObjectContext事件和鑄造發件人ObjectContext

試試這個:

public class MyContext : DbContext 
{ 
    private static EntityState[] states = new EntityState[] 
     { 
      EntityState.Added, 
      EntityState.Modified, 
      EntityState.Deleted, 
     }; 

    ... 

    public override int SaveChanges() 
    { 
     // If Entires<IMyContract> doesn't work use Entries() and check type 
     // inside the loop 
     foreach(var entry in ChangeTracker.Entries<IMyContract>() 
              .Where(e => states.Contains(e.State)) 
     { 
      ... 
     } 
    } 
} 
+0

我用這個來獲取Context對象:var context =((IObjectContextAdapter)database).ObjectContext; context.SavingChanges + = new EventHandler(context_SavingChanges); – Attilah 2011-04-04 07:39:12

+0

問題不在於ObjectContext,而在於它永遠不會評估爲真:DiscountEntity discountEntity = entry.Entity as DiscountEntity; – Attilah 2011-04-04 07:52:17

+0

如果您調試您的應用程序,您在監視窗口中看到了什麼類型的實體? – 2011-04-04 08:04:26