I create few entities in Entity Framework. They are automatically added.
Question 1: Is it normal that MyEntity.CreateMyEntity automatically adds entity to the context?
Now, I want to save them but if they violate the database constraints I get exception, nothing is persisted — RIGHT, BUT — these objects remain in the ObjectContext which I do not want.
I tried to run that code as:
using (var t = new TransactionScope()) {
...create entities...
try
{
context.SaveChanges();
t.Complete();
context.AcceptAllChanges();
}
catch
{
MessageBox.Show("Ooops");
}
}
but even if I ran it in the transaction, these entities remain in the context.
Question 2: What am I missing? Do I have to remove them manually?
Another option to avoid unwanted objects without having to dispose the context is to manually detach them after you have committed the changes to the DB using
Detach():Be careful with related entities though, if your entity has related objects the related entities will not be detached automatically.