Jannik
Jannik

Reputation: 2429

Undo DbContext.Add()

I have the problem, that I've added a entity to my DbContext using _db.Article.Add(artícle), but want to UNDO this before I'm executing _db.SaveChanges.

I haven't found anything, but I tried to use _db.ChangeTracker sadly not figuring it out yet. Further more _db.Entry(article).State = EntityState.Deleted or _db.Article.Remove(article) will not work either, because the entity isnt in the Database yet...

Is there any possibility to delete it out of the list of changes?

Upvotes: 2

Views: 809

Answers (2)

undefined
undefined

Reputation: 34299

Remove works just fine, the following produces no change in SQL (no insert or delete statements)

class Program
{
    static void Main(string[] args)
    {
        using (var ctx = new MyContext())
        {
            var entity = new MyEntity();

            ctx.MyEntities.Add(entity);
            ctx.MyEntities.Remove(entity);

            ctx.SaveChanges();
        }
    }
}

public class MyContext : DbContext
{
    public DbSet<MyEntity> MyEntities { get; set; }
}

public class MyEntity
{
    public int Id { get; set; }
}

This is because SQL is not generated until the savechanges call in EF. Its not until this point that EF evaluates the entire graph and persists changes which dont match its initial snapshot to the database.

Upvotes: 1

Joachim Isaksson
Joachim Isaksson

Reputation: 181037

You can make use of the explicit implementation of DbContext.IObjectContextAdapter.ObjectContext to get to the underlying ObjectContext and Detach your entity, something like;

((IObjectContextAdapter)_db).ObjectContext.Detach(article);

A syntactically cleaner way would be to extend your DbContext with a method;

public class MyDbContext : DbContext 
{
    public void Detach(object entity) { ObjectContext.Detach(entity); }
}

...which would allow you to simply do;

_db.Detach(article);

Upvotes: 2

Related Questions