Entity framework 在域服务插入方法中添加实体
我有两个实体,Entity framework 在域服务插入方法中添加实体,entity-framework,wcf-ria-services,domainservices,Entity Framework,Wcf Ria Services,Domainservices,我有两个实体,Parent和Child,在客户端我创建Parent,然后调用context.submitChanges 在InsertParent(Parent-Parent)中的服务器端,我执行以下操作: InsertParent(Parent parent) { Child child = this.ObjectContext.Childs.CreateObject(); parent.child = child; if ((parent.EntityState != E
Parent
和Child
,在客户端我创建Parent
,然后调用context.submitChanges
在InsertParent(Parent-Parent)
中的服务器端,我执行以下操作:
InsertParent(Parent parent)
{
Child child = this.ObjectContext.Childs.CreateObject();
parent.child = child;
if ((parent.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(parent, EntityState.Added);
}
else
{
this.ObjectContext.Parents.AddObject(parent);
}
}
现在我有两个问题
在if-else之前,Parent.id
是0,在其之后仍然是0,但在数据库中填充了它
另一个是,Child
已保存,但Child.ParentId
为0
我不明白为什么
实现这种行为的正确方法是什么?我是否应该直接在上下文中调用SaveChanges()
?是的,您应该使用SaveChanges(),因为这是将数据持久保存到数据库中的方法
您还需要检查parents.Id列和childs Id列是否设置为identity和primary key,以及这两个表之间的关系。检查以确保edmx中Parent.Id上的StoreGeneratedPattern属性设置为identity。这应该确保在插入时使用新值更新它 我还将把它包装在一个事务中,以便您可以在设置父id后添加您的子项
using(var scope = new TransactionScope()){
ObjectContext.Parents.AddObject(parent);
ObjectContext.SaveChanges(); //parent.id assigned
parent.child = ObjectContext.Child.CreateObject();
ObjectContext.SaveChanges();
scope.Complete(); // commit transaction
}
你能详细说明一下吗?如果在添加父对象之前调用SaveChanges(),则child.ParentID将为0?如果在添加父对象之前调用SaveChanges,则不会执行任何操作。这个非常简单的示例演示了如何将对象及其子对象添加到数据库中。EntityFramework允许您同时添加这两个对象,甚至不需要使用事务。但是您答案中的标识部分是正确的,我忘记了。对于EF的当前版本,我可能是错的,但是我相信如果您使用的是POCO实体,并且它们没有配置为更改跟踪,那么您确实需要使用事务进行包装。但是,如果您只是使用默认的、EF生成的实体,那么您不需要事务,一个
SaveChanges
应该可以工作,这是正确的。