Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

c# - 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:DocumentsVisual Studio 2012ProjectsWpfApplication9WpfApplication9MainWindow.xaml.cs 49 31 WpfApplication9`

Also suggest which one is better. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...