Reputation: 333
I've created a simple Form containing two TextBoxes for name and age, and a button to submit. I added a "Local Database" to my project called Sample.sdf
.
I've created a table called Customers
and added three columns: Id
, Name
, and Age
.
I've set the Id
column as the primary key but didn't set it as an identity column.
Then, I added an "ADO.NET Entity Data Model" called SampleEntities
. I selected "Generate from database" and chose the Sample.sdf
. I've selected the table and clicked Finish.
In my Button_Click
event I've done:
using (SampleEntities se = new SampleEntities())
{
Customer c = new Customer();
c.Id = FindNextId();
c.Age = Convert.ToDouble(txtAge.Text);
c.Name = txtAge.Text;
se.AddToCustomers(c);
se.AcceptAllChanges();
se.SaveChanges();
}
MessageBox.Show("Done");
I'm getting the "Done" message with no problems, but the records are not showing in the Server Explorer - Customers table - Show Table Data option.
Note: I know that in runtime, the sdf file is located in my debug folder. I'm checking both the sdf file in the project directory, and the sdf file in the debug folder, and neither have any records. Furthermore, I have set my sdf file property "Copy To Output Directory" to "Copy if newer".
So my question is, where is the customer row?
Upvotes: 2
Views: 637
Reputation: 13158
The issue is your AcceptAllChanges
call. You do not need to call it; just call SaveChanges
.
using (SampleEntities se = new SampleEntities())
{
Customer c = new Customer();
c.Id = FindNextId();
c.Age = Convert.ToDouble(txtAge.Text);
c.Name = txtAge.Text;
se.AddToCustomers(c);
se.SaveChanges();
}
MessageBox.Show("Done");
You only need to call AcceptAllChanges
if you call one of:
SaveChanges(false)
SaveChanges(SaveOptions.None)
SaveChanges(SaveOptions.DetectChangesBeforeSave)
When you call SaveChanges()
, (with no arguments), "accepting all changes" happens automatically.
Upvotes: 2
Reputation: 8647
If you need to call the AcceptAllChanges
method (1), you must save changes before accepting them.
se.SaveChanges();
se.AcceptAllChanges();
The AcceptAllChanges
method iterates all the ObjectStateEntry objects within the ObjectStateManager that are Added or Modified, and then sets the state of the entry to Unchanged. The Deleted items become detached.
So when you call SaveChanges
after AcceptAllChanges
, there is nothing to save.
(1) As @Sahuagin pointed out, there is generally no need to call the AcceptAllChanges
method. If you call SaveChanges()
you don't need to call AcceptAllChanges
at all.
You only must call the method when you use the SaveChanges(SaveOptions)
method and do not specify the AcceptAllChangesAfterSave
in SaveOptions
.
Upvotes: 2