【问题标题】:ORM, DataBinding to DataGridView: inserting/deleted new rows not saved to the databaseORM,DataBinding到DataGridView:插入/删除未保存到数据库的新行
【发布时间】:2011-06-02 13:45:11
【问题描述】:

我对 ORM 很陌生,我目前正在尝试 Telerik OpenAccess ORM,但问题实际上可能并非特定于该 ORM,而且我还没有完全确定该 ORM。

我想要实现的是绑定一个 DataGridView 以显示客户对象的集合,这些对象显示客户表中的所有客户。

我已将其绑定到 BindingSource 并将 BindingSource 绑定到 DataGridView 控件。

我可以成功修改现有项目(使用 OpenAccess ORM 的 SaveChanges 方法)。当我保存时,内容会按预期保存回数据库中。

但是,如果我从 DataGridView 中删除一行或添加新行,它们不会保存到数据库中,根本没有错误消息或异常。

理想情况下,我希望能够使用 ORM 执行所有可能的 CRUD 操作,就像我可以使用典型的 DataTable 执行此操作...

执行绑定的代码如下所示:

        List<Customer> ukCustomers = (from c in diagrams.Customer
                              where c.Country == "UK"
                              select c).ToList();

        customersBindingSource.DataSource = ukCustomers;
        customersBindingSource.AllowNew = true;

我目前的猜测是用户添加到 DataGridView 的新行不是列表的一部分,而是“独立”客户实例?我原以为它们会自动添加到列表中。删除的行也是如此,我认为这些行会自动从列表中删除,并且 ORM 中的 SaveChanges 方法能够获取它吗?

我应该做的不仅仅是绑定吗? 有没有人在这方面取得过任何成功,总的来说,您使用 WinForms 进行数据绑定的体验有多成功,以及您选择的 ORM(不一定是 Telerik 的)?

谢谢。

【问题讨论】:

    标签: c# winforms data-binding datagridview telerik


    【解决方案1】:

    你的怀疑是正确的。您将网格绑定到对象的“独立”列表,虽然每个对象都是自跟踪的,但列表不是。这就是为什么对现有对象的更改按预期工作,但添加/删除却不能。

    一种解决方案是使用可观察集合而不是标准列表。然后您可以处理相同的绑定,但通过根据需要从上下文中添加/删除项目来响应添加/删除事件。

    基本例子:

      private PropertyManagerModel.DemoDBEntityDiagrams context;
        public Form1()
        {
            InitializeComponent();
            context = new DemoDBEntityDiagrams();
            LoadCommunities();
        }
    
       private void LoadCommunities()
        {         
            var communityList = new ObservableCollection<Community>(context.Communities);
            communityList.CollectionChanged += new NotifyCollectionChangedEventHandler(communityList_CollectionChanged);
            this.dataGridView1.DataSource = new BindingSource() { DataSource=communityList};
        }
    
        void communityList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
                context.Add(e.NewItems);
    
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
                context.Delete(e.OldItems);
    
            context.SaveChanges();
        }      
    

    据我所知,所有 ORMS 都是如此。希望这会有所帮助!

    问候,

    约书亚·霍尔特

    【讨论】:

    • DataGridView 上有组合框时不起作用。在这些情况下,ObservableCollection 会持续触发并产生 DataError 异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 2011-11-16
    • 2014-01-18
    相关资源
    最近更新 更多