在EFF中将EF绑定到DataGrid

时间:2014-01-18 19:37:49

标签: c# wpf entity-framework entity-framework-6

我是EF的新手并且遇到了问题。

我有一个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}"(从记忆中写,借口小错误) 然后我将每个列绑定到Product类中的确切属性。

OnLoad方法使用数据库上下文,就像这样

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

它正确显示所有记录,但是,如果我添加或编辑记录,它不会影响数据库:( 我已经读过ToList打破了与EF的连接,这就是我无法添加/编辑的原因,但是没有任何可行的修复方法。有什么想法吗?

顺便问一下,我在哪里放置ShowAllProductsForCustomer(int id)的方法?我把它们放在产品类中吗?

2 个答案:

答案 0 :(得分: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();上下文更新数据库的方法。

答案 1 :(得分:0)

这实际上非常简单,如果需要,您可以非常轻松地绑定数据。

试试这个:

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

我已经把它写在了我的头顶,但希望你能得到你想要做的事情的要点。

此致 -G。