I created a .MDF database in my WPF application.
I then generated LINQ-to-SQL classes and used LINQ get all the customers.
Then I run through them and change each of their last names.
However, when I call SubmitChanges, the database remains unchanged.
I thought that was the purpose of SubmitChanges(), to submit changes to the database?
What am I missing, how do I "submit changes" back to my database?
public Window1()
{
InitializeComponent();
Main2DataContext _db = new Main2DataContext();
var customers = from c in _db.Customers
select c;
foreach (var customer in customers)
{
customer.LastName = "CHANGED lastname"; //ListBox shows changes
}
_db.SubmitChanges(); //does NOT save to database (???)
}
I think I know what the problem is. Are you using a local .mdf file? If that's the case, check your bin/debug folder. I bet you have a database in there with the changes. I think you have an .mdf file in your project that is getting copied to the bin/debug folder everytime you build. Therefore the changes are getting saved to the copy, and you're not seeing it reflected in the copy that resides directly in your project.
Make sure that your _db isn't getting reset to a new context at any point between the retrieval and change, if so well that is the problem. Also you can simplify your assignment of your datasource by doing TheListBox.ItemsSource = _db.Customers;
. I have many places in current code where I am doing exactly what you describe and the changes are propogating fine. An additional suggestion, setup logging on your context (set the _db.Log
to some writer, I generally use the Console.Out
so I can watch changes in the output window while debugging) so you can see the changes that actually do occur when you call SubmitChanges()
.