3

Possible Duplicate:
What is the difference between IDbSet.Add and DbEntityEntry.State = EntityState.Added?

What's the difference between DbSet.Add(entity) vs entity.State = EntityState.Added? I some examples using both to add an entity to DbContext but not sure which is the preferred one.

I saw some test the "Detached" condition and decide which to use in their repository implementation.

    public void Add(T entity)
    {
        var entry = DbContext.Entry(entity);
        if (entry.State == EntityState.Detached)
        {
            DbSet.Add(entity);
        }
        else
        {
            entry.State = EntityState.Added;
        }
    }

Anyone idea? Thanks!

Community
  • 1
  • 1
JeeShen Lee
  • 3,476
  • 5
  • 39
  • 59

1 Answers1

2

There isn't any difference between either of these options as under the hood they are both calling the same method (ie AddObject on an ObjectContext).

Judo
  • 5,167
  • 3
  • 24
  • 34