2014-12-02 72 views
0

我有,我用我的EF上下文從數據庫將數據加載到一個DataGridView,以使用戶能夠做出一些改變一個用戶控件:用戶控件和EF上下文處理

public partial class MyUserControl: UserControl 
    { 
     MyEntities context; 

     public ViewMasterData() 
     { 
      InitializeComponent(); 
      createComboBoxTable(); 
     } 

     private void MyUserControl_Load(object sender, EventArgs e) 
     { 
      context = new MyEntities(); 
     } 

    // Other methods to fill the dataGridView and Save the data back to the DB 

     private void SaveChanges() 
     { 
      context.SaveChanges();     
     } 
    } 

我想當我離開UserControl時(即導航到另一個UserControl)處理上下文,但似乎在UserControl的Dispose方法(在代碼生成的)上調用context.Dispose()不起作用,因爲它僅在我關閉了整個WinForm。我無法使用「使用」,因爲我需要保持上下文打開才能執行更改並保存。

問題是:當我離開UserControl時,如何正確地處理上下文? 感謝!

回答

1

我認爲保持EF環境開放被認爲是不好的做法。相反,只要你需要,就創建一個你的上下文的新實例。實際上,在using語句中包裝上下文將通過垃圾收集器自動處理它。

public partial class MyUserControl: UserControl 
{ 
    // MyEntities context; i dont need this 

    public ViewMasterData() 
    { 
     InitializeComponent(); 
     // createComboBoxTable(); 
    } 

    private void MyUserControl_Load(object sender, EventArgs e) 
    { 
     using (var context = new MyEntitiesContext()) 
     { 
      createComboBoxTable(context.MyEntities.ToList()); 
     } 
    } 

    private void SaveNewMyEntity(MyEntity newEntity) 
    { 
     using (var context = new MyEntitiesContext()) 
     { 
      // some logic here to check for uniqueness etc 

      context.MyEntities.Add(newEntity); 
      context.SaveChanges(); 
     } 
    } 

    private void UpdateExistingMyEntity(MyEntity updatedEntity) 
    { 
     using (var context = new MyEntitiesContext()) 
     { 
      context.Entry(updatedEntity).State = EntityState.Modified; 
      context.SaveChanges(); 
     } 
    } 
} 

UPDATE:

我同意它能夠更好地一次性添加多個實體,所有你需要的是一個foreach循環,這或許表明,如果一個myEntity所實例已更新了一點布爾屬性。這樣的事情是一個可能的解決方案:

private void UpdateExistingMyEntity(IEnumerable<MyEntity> updatedEntities) 
{ 
    using (var context = new MyEntitiesContext()) 
    { 
     foreach(MyEntity e in updatedEntities) 
      context.Entry(e).State = EntityState.Modified; 

     context.SaveChanges(); 
    } 
} 

當用戶點擊Save按鈕...

private void saveBtn_Click(object sender, RoutedEventArgs e) 
{ 
    IEnumerable<MyEntity> updatedEntities = myGridData.Where(o => o.HasBeenUpdated == true); 

    UpdateExistingMyEntity(updatedEntities); 

    foreach(MyEntity e in updatedEntities) 
     e.HasBeenUpdated = false; 
} 
+0

感謝您的反饋。我需要在DataGridView中對多個記錄進行更改,然後在最後單擊Save。我如何用你提出的方法來實現這一點?如何讓EntityState.Modified用戶更改/添加的所有recoreds? – andrew0007 2014-12-02 15:01:01

+0

很高興幫助,看到我更新的答案。 – Fredrik 2014-12-03 09:35:53

0

直接在用戶控制使用EF是不好的做法。在另一個問題中查看here