linq to sql update mulitple rows

2019-09-03 07:45发布

问题:

I am trying to update a sql table using linq to sql :

Querying the database using Linq to SQL I am able to load the data into a gridview in the UI in a WPF application. So I have a check box associated with each row. The table has EmpName and Ability as two columns. So when user checks the check box associated with the row/rows I have to update the value in the table back in the sql DB.

Here is the code for my check box checked :

    private void EmployeeName_Checked(object sender, RoutedEventArgs e)
    {
      DataDataContext dc = new DataDataContext();

        foreach (var item in empListView.SelectedItems)
        {


        EmpList updateList  = (from p in dc. EmpList
                                          where p.able == No
                                          select p).FirstOrDefault();


            if(updateList.able==NO)
            updateList.able = YES;

        }

        dc.SubmitChanges();
        empListView.ItemsSource = dc.EmpLists.ToList();
    }

EmpList here is the one created when I added the linqtosql class from the designer. So I am trying to update the same list which inturn submits the changes to the DB.

Question: I am able to select the rows based on the selected checkboxes in the gridview and I am able to loop through the selected items, but I am unable to update all the selected rows..only few are updating...I would be glad if some one can look at the code and guide me if theres any thing wrong with the query.

Ultimately, I have to update all the selcted rows based on their current values in the colum Ability of the gridview.

回答1:

Here is a good article on Batch Updates and Deletes with LINQ to SQL http://www.aneyfamily.com/terryandann/post/2008/04/Batch-Updates-and-Deletes-with-LINQ-to-SQL.aspx

Maybe this gives you an idea or a pointer...



回答2:

DataDataContext dc = new DataDataContext(); needs to be moved outside of the foreach loop. Currently it should not compile because it is out of scope. I don't understand how you are linking the item selected to the item you are pulling from the data set, you are just pulling the first one? Does your item have an Id or something to grab?