【问题标题】:Entity Framework CRUD operations on a datagrid数据网格上的实体框架 CRUD 操作
【发布时间】:2011-03-12 08:25:27
【问题描述】:

我有一个List<T> 绑定到一个数据网格,并试图弄清楚如何将所有更改保存到数据库(使用实体框架),而不是一次只保存一行;或者,至少是一种将更改从数据网格提交到数据库的更好方法。我正在使用 MVVM 模式。 就保存一行而言,这是我所拥有的:

    private static PROJECT_EXPENSEEntities _service;

    //The default constructor
    public ProjectExpenseItemsRepository()
    {
        if (_service == null)
        {
            _service = new PROJECT_EXPENSEEntities();
        }
    }

  public void AddProjectExpenseItems(int projectExpenseID)
        {
            project_expense_items p = new project_expense_items();
            if (entityList != null)
            {
                p.project_expense_id = projectExpenseID;
                p.item_number = entityList.ItemNumber;
                p.item_description = entityList.ItemDescription;
                p.item_unit_price = entityList.ItemUnitPrice;
                p.item_qty = entityList.ItemQty;
                p.supplier_name = entityList.SupplierName;
                p.create_date = System.DateTime.Today;
                _service.AddObject("project_expense_items", p);
                _service.SaveChanges();
            }
        }

但是,我希望一次将更改发送到数据网格中的所有行:

    public void AddProjectExpenseItems(List<ProjectExpenseItemsBO> entityList, int projectExpenseID)
    {
        project_expense_items p = new project_expense_items();
        if (entityList != null)
        {
// not sure what goes here, do I need a loop for each item in the list?
// I have a feeling I am going in the wrong direction with this...

            _service.AddObject("project_expense_items", entityList);
            _service.SaveChanges();
        }
    }

我在网上没有找到很多好的例子。如果有人能指出一个例子,我会很感激。

【问题讨论】:

  • 如果您使用 RIA,有一种简单的方法可以做到这一点。只需调用 DomainContext 类的 SubmitChanges。

标签: wpf entity-framework mvvm datagrid crud


【解决方案1】:

是的。在添加/修改/删除项目后,您可以简单地遍历您的列表和 SaveChanges。

当然,您可能希望从数据库加载和显示项目,因此直接绑定到EntityCollection&lt;project_expense_items&gt; _service.project_expense_items 会比使用分离实体列表更有效。 Entity Framework 将为您跟踪更改。

看到这个:http://msdn.microsoft.com/en-us/library/bb896269.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多