4

I am using Visual Studio 2012. I have a very simple Products table in a Local Database (cleverly named Database1). It has two fields: id and Name. I preloaded it with a few test data.

The following code should update the Name of the first Product. Internally, it does. I can retrieve all Products and see that the first one's Name is "Shirt." But the change is never flushed to the database. The record is never updated. Examining the database reveals that the name has not been changed.

My question is simple: Why are changes not being sent to the database?

using (var context = new Database1Entities())
{
    var products = context.Products;

    products.First().Name = "Shirt";
    context.SaveChanges();
}

Thanks in advance.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

EDIT:

I tried my best to enter the full code and output here. But, no matter what I do, I continue to get the "Your post appears to contain code that is not properly formatted" error message. After 30 minutes I am giving up.

EDIT:

The code and output is here: http://pastebin.com/GmQtwAND

Joel Finkel
  • 116
  • 1
  • 7
  • Did you make sure that change tracking is enabled on the context? – dksh Jun 05 '13 at 03:43
  • But are you changing any values? Shirt = Shirt looks like the same to me... – ErikEJ Jun 05 '13 at 07:30
  • Yes, context.Configuration.AutoDetectChangesEnabled = true. Also, the initial value, which I pre-loaded in the database, is "Hat," and that value remains in the database even after setting it to "Shirt." – Joel Finkel Jun 05 '13 at 13:14

2 Answers2

4

I discovered the issue...and its solution.

The "Copy to Output Directory" property of the database file was set to "Copy always." This, of course, meant that every time the application was built, a fresh copy was placed into the Bin directory. The fix was to set it to "Copy if newer." Doh.

In other words, the changes were being persisted in the database, but then the database was being clobbered when the application got rebuilt.

Joel Finkel
  • 116
  • 1
  • 7
2

Well this could mean that you're not tracking changes, how about you try to set the State to -> Modified and see if it's going to work:

var product = products.First();
product.Name = "Shirt";
product.State = EntityState.Modified;
context.SaveChanges();

If you want to enable it for the context you can do it like this:

context.Configuration.AutoDetectChangesEnabled = true;
Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79
  • 1
    Thanks. "product" has no "State" property. At least none that I see. And, yes, context.Configuration.AutoDetectChangesEnabled = true. By the way, "SaveChanges()" returns 1, which I assume is the count of updated records. – Joel Finkel Jun 05 '13 at 13:18