Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between dbcontext.Add and dbcontext.AddObject

I am beginner at WPF. I want to know that what is difference between dbcontext.Add and dbcontext.AddObject.

private void AddButton_Click(object sender, RoutedEventArgs e)
{
        Name employee = new Name();
        employee.Name1 = "Test";
        dataContext.Names.AddObject(employee);
}

I want to achieve this dbcontext.AddObject(). But I get an error:

'System.Data.Entity.DbSet' does not contain a definition for 'AddObject' and no extension method 'AddObject' accepting a first argument of type 'System.Data.Entity.DbSet' could be found (are you missing a using directive or an assembly reference?) C:\Documents\Visual Studio 2012\Projects\WpfApplication9\WpfApplication9\MainWindow.xaml.cs 49 31 WpfApplication9`

Also suggest which one is better. Thank you.

like image 408
Zoya Sheikh Avatar asked Aug 14 '13 12:08

Zoya Sheikh


2 Answers

Actually you are talking about AddObject method of ObjectSet<TEntity> class which was used by old ObjectContext. But since Entity Framework 4 we have DbContext class (which is a wrapper over old ObjectContext). This new class uses DbSet<TEntity> instead of old ObjectSet<TEntity>. New set class has method Add.

So, back to differences. Old implementation invoked AddObject method of ObjectContext:

public void AddObject(TEntity entity)
{
    Context.AddObject(FullyQualifiedEntitySetName, entity);
}

New implementation does same thing (see action parameter):

public virtual void Add(object entity)
{
    ActOnSet(() => ((InternalSet<TEntity>) this).InternalContext.ObjectContext.AddObject(((InternalSet<TEntity>) this).EntitySetName, entity),  
              EntityState.Added, entity, "Add");
}

As you can see same ObjectContext.AddObject method is called internally. What was changed - previously we just added entity to context, but now if there is state entry exists in ObjectStateManager, then we just changing state of entry to Added:

if (InternalContext.ObjectContext.ObjectStateManager.TryGetObjectStateEntry(entity, out entry))
{
    entry.ChangeState(newState); // just change state
}
else
{
    action(); // invoke ObjectContext.AddObject
}

Main goal of new API is making DbContext easier to use.

like image 111
Sergey Berezovskiy Avatar answered Oct 01 '22 19:10

Sergey Berezovskiy


Call AddObject on the ObjectContext to add the object to the object context.

Do this when the object is a new object that does not yet exist in the data source.

When you create a new object that is related to another object in the object context, add the object by using one of the following methods: Call the Add method on the EntityCollection and specify the related object.

like image 40
Cornel Marian Avatar answered Oct 01 '22 19:10

Cornel Marian