是什么dbcontext.Add和dbcontext.AddObject之间的区别 [英] What is difference between dbcontext.Add and dbcontext.AddObject
问题描述
我是初学者在WPF。我想知道,是什么 dbcontext.Add
和 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);
}
我想实现这个 dbcontext.AddObject()
。但我得到一个错误:
I want to achieve this dbcontext.AddObject()
. But I get an error:
System.Data.Entity.DbSet不包含ADDOBJECT',没有扩展方法'ADDOBJECT接受第一种类型System.Data.Entity.DbSet'的参数的定义可以找到(是否缺少?using指令或程序集引用)C:\文档\的Visual Studio 2012 \项目\ WpfApplication9 \ WpfApplication9 \ MainWindow.xaml.cs 49 31 WpfApplication9`
'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.
推荐答案
其实你是在谈论 ADDOBJECT
对象集和其中的方法; TEntity>
类,它是用旧的ObjectContext
。但由于实体框架4,我们有的DbContext
类(这是一个包装过的老的ObjectContext
)。这个新的类使用 DbSet< TEntity>
代替旧对象集< TEntity>
。新的组类有方法添加
。
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
.
所以,回到差异。旧的实现调用 ADDOBJECT
的方法的ObjectContext
:
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");
}
正如你可以看到同样的 ObjectContext.AddObject
方法在内部调用。是什么改变了 - pviously我们刚才添加$ P $实体背景,但现在如果有表项存在于ObjectStateManager,那么我们就改变进入状态,以添加
:
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
}
新的API主要目标是使的DbContext
更容易使用。
这篇关于是什么dbcontext.Add和dbcontext.AddObject之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!