2014-01-18 112 views
0

我是EF新手,並且遇到問題。將EF綁定到WPF中的DataGrid

我有一個WPF應用程序,它包含DataGrid。比方說,它包含了產品和其他信息的列表,因此類看起來像

class Product 
{ 
    public Product() 
    { 
     products = new ObservableCollection<Product>(); 
    } 

    public int ProductId (get; set;} 
    public string Name {get; set;} 
    public string Supplier {get; set;} 
    public virtual ObservableCollection<Product> products {get; set;} 
} 

現在我想申辦這個類網格,所以當有人添加/編輯一行將自動更新數據庫(或上下文菜單中刪除)

因此,在xaml中有ItemsSource = "{Binding}"(寫從內存中,原諒小錯誤) 然後,我已經綁定每一列精確屬性在類產品。

OnLoad方法使用數據庫上下文和是這樣

Product product = new Produxt(); 
Datagrid1.DataContext = ctx.Product.products.ToList(); 

它顯示所有記錄正常,但是呢,如果我添加或編輯記錄,它不會影響數據庫:( 我已經讀取ToList斷開與EF的連接,這就是爲什麼我不能添加/編輯,但沒有任何工作修復的任何想法?

順便說一句,我在哪裏把方法例如ShowAllProductsForCustomer(int id)?我把它們放在Products類中嗎?

回答

0

這實際上很簡單,如果你願意,你可以很容易地綁定數據。

試試這個:

private void FillData() 
    { 
     var q = (from a in ctx.Product 
       select a).ToList(); 
     Datagrid1.ItemsSource = q; 
    } 

我已經寫了這個把我的頭頂部,但希望你得到你正在嘗試做的要點。

Regards, G.

0

試試這個

ctx.Product.products.Load(); 
//create a bindings source on your form, then use it here 
myBindingsSource.DataSource = ctx.Product.products.Local.ToBindingList(); 
//this can also be done in the properties of the grid on the form 
Datagrid1.DataSource = myBindingsSource; 

我在做類似的事情。 只需執行SaveChanges();更新數據庫的上下文方法。