wpf - 数据网格上的 Entity Framework CRUD 操作

标签 wpf entity-framework mvvm datagrid crud

我有一个 List<T>绑定(bind)到数据网格并试图弄清楚如何将所有更改保存到数据库(使用 Entity Framework ),而不是一次只保存一行;或者,至少是一种将更改从数据网格提交到数据库的更好方法。我正在使用 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();
        }
    }

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

最佳答案

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

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

见:http://msdn.microsoft.com/en-us/library/bb896269.aspx

关于wpf - 数据网格上的 Entity Framework CRUD 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3187043/

相关文章:

entity-framework - "update-database" Entity Framework 代码先不加表

c# - WPF 实时图表无法正确呈现

c# - ASP.NET MVC 4,EF5,模型中的唯一属性 - 最佳实践?

.net - azure辅助角色中的DbConfiguration.SetConfiguration

mvvm - 添加 View 不会调用MEF导入语句

wcf - 通过带有私有(private)字段的 wcf 服务发送对象的问题

WPF:将 DataGrid 放入 ComboBox

wpf treeviewitem鼠标双击

c# - ReactiveUI 验证不会引发错误通知并且无法 BindValidation

android - 在使用数据绑定(bind)和 MVVM 将新数据放入 Activity 之前,旧 View 数据会短暂出现在 Activity 中