2011-05-15 25 views
0

是否有人設法使用DataSource屬性和ADO.NET實體框架綁定DataNavigator和DataGrid,以便添加和刪除(+和 - 數據導航器中的按鈕)。工作?我有這個問題,每次點擊DataNavigator的添加按鈕時,EntityState總是被設置爲分離。我無法弄清楚,如何將這個分離的實體添加到DataContext中。實體框架和DataNavigator

我的代碼很簡單(使用靜態會話類和部分類):

internal class Session 
{ 
    private static Entities _entities; 

    public static Entities Entities 
    { 
     get { return _entities ?? (_entities = new Entities()); } 
     set { _entities = value; } 
    } 
} 

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
     InitData(); 
    } 

    private void InitData() 
    { 
     gridControl1.DataSource = Session.Entities.SomeObjects; 
     dataNavigator1.DataSource = Session.Entities.SomeObjects; 
    } 
} 

public partial class SomeObjects 
{ 
    public SomeObjects() 
    { 
     PropertyChanged += SomeObject_PropertyChanged; 
     ObjectId = Guid.NewGuid(); 
    } 

    private void SomeObject_PropertyChanged(object sender, PropertyChangedEventArgs e) 
    { 
      Debug.WriteLine(EntityState); // when i change a existing record in the grid, EntityState is set to modified and can be saved easily using SaveChanges. But when i add a new entity, EntityState is always set to detached. 
    } 
} 

幫助的感謝!

-Christian

回答

2

我認爲你應該使用BindingSource控制,而不是使用DataSource和處理AddingNew事件致電AddObject手動設置國Added

DataGrid不知道關於數據源的任何信息,所以它不能與實體框架上下文/設置和添加對象進行通信。您必須手動執行此操作,並且需要一些事件來處理添加新記錄的時間。我相信AddingNewBindingSource是要走的路。