views:

283

answers:

1

I have a WPF app with a local .MDF file on which I created an Entity Framework class model.

Retrieving entities from the database works fine:

//get entities
using (var context = new TestDataEntities1())
{
    var customers = from c in context.Customers
                    select c;
    foreach (var customer in customers)
    {
        TheCustomers.Add(customer);
    }
}

However, updating and adding and deleting* do not. There is **no error, the debugger steps right through, no messages in Output, but the data in the database table remains unchanged.

//update entity
using (var context = new TestDataEntities1())
{
    var customer = (from c in context.Customers
                    where c.Id == 1
                    select c).FirstOrDefault();
    customer.FirstName = DateTime.Now.ToString();
    int num = context.SaveChanges(); //returns 1, table unchanged

}

//add entity
using (var context = new TestDataEntities1())
{
    var customer = new Models.Customers();
    customer.FirstName = "Ned";
    customer.LastName = "Newton";
    context.AddToCustomers(customer);
    int num = context.SaveChanges(); //returns 1, table unchanged
}

//delete entity
using (var context = new TestDataEntities1())
{
    var customer = (from c in context.Customers
                    where c.Id == 2
                    select c).FirstOrDefault();
    context.Detach(customer); // table unchanged
}

What do I have to do to get Entity Framework to also update and add entities to the database table?

+3  A: 

First, SaveChanges does not guarantee an update. It returns the # of rows changed. So check the return value. If it's 0, then the EF doesn't think it made an update. If it's > 0 then it does.

Second, you should profile SQL to see what the EF is sending.

If the result of SaveChanges is 0, then the cause is almost certainly that the EF doesn't think anything in the context is modified. Why that would be depends upon how your changes are tracked. Your code above looks correct for insert, but for update the ApplyPropertyChanges is superfluous and should be removed.

If the EF is sending SQL but the DB is doing nothing with it, you should examine the SQL for a fix.

Craig Stuntz
SaveChanges for both update and add return a 1, but the table remains unchanged, I changed the values in the table to make sure this is actually the same table from which the records are successfully being retrieved, it is, what else could be causing this?
Edward Tanguay
Profile the SQL. (If using SQL Server, use SQL Profiler. If not, use a tool for your DB server.) What do you see?
Craig Stuntz
SORRY, I got bit by the your-mdf-file-gets-copied-to-the-bin-directory-and-is-not-the-same-as-the-mdf-file-in-visual-studio-dummy error: http://stackoverflow.com/questions/875995/entity-framework-wont-persist-data-in-sql-express-mdf/885027#885027, thanks for the ApplyPropertyChanges tip!
Edward Tanguay