Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top