Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between DbSet.Add(entity) and entity.State = EntityState.Added [duplicate]

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!

like image 466
JeeShen Lee Avatar asked Dec 17 '25 02:12

JeeShen Lee


1 Answers

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).

like image 193
Judo Avatar answered Dec 19 '25 22:12

Judo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!