Updating Data with LINQ and BindingSource
I am writing a relatively simple Windows Form app that is supposed to act as a front-end (adding, editing, removing entries) for a SQL Server database we have. I have a TextBox for each column in the table, and a ListBox to list all the entries (by first and last name). The TextBoxes get populated with the data of whichever entry is selected in the ListBox.
I am having some difficulty updating entries in the DB using the BindingSource. Here is the code th开发者_运维百科at I am currently (unsuccessfully) using:
DBDataContext dc = new DBDataContext();
Entrys e = (Entry)EntryBindingSource.Current;
dc.Entrys.Attach(e);
dc.Entrys.InsertOnSubmit(e);
dc.SubmitChanges();
With this code I get an exception that the entry already exists, which makes sense, but I don't know how to tell it that I want to update that entry with the new data.
I know how you can manually update each entry, but since I have 10 different columns, that would be a relatively large if/else tree (checking if each textbox's value is different than the BindingSource's value for that entry). Deleting and then re-adding that entry just seems like bad form to me. I'm sure there's a better way of doing it.
I highly doubt you are doing this right. Using Linq you should first try to retrieve your entry/check for its existence, then make your changes, and then only submit them. Updating this way should be pretty straightforward. the "InsertOnSubmit" call is in my opinion very suspicious.
精彩评论