开发者

Entity Framework CRUD operations on a datagrid

I have a List<T> bound to a datagrid and am trying to figure out how to save all the changes to the database (using Entity Framework), not just one row at a time; OR, at least a better way to commit changes from the datagrid to the database. I am using the MVVM pattern. Here is what I have as far as saving one row:

    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);
开发者_JAVA百科                _service.SaveChanges();
            }
        }

However, I would prefer to send the changes to all rows in the datagrid at once:

    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();
        }
    }

I haven't found many good examples on the web. If someone could point me to an example I'd appreciate it.


Yes. You can simply loop through your list and SaveChanges once after adding/modifying/deleting the items.

Of course, you would likely want to load and display items from the database, so binding directly to EntityCollection<project_expense_items> _service.project_expense_items would be more effective than using a list of detached entities. Entity Framework will track changes for you.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜