我正在尝试编写一个WCF方法,该方法将从客户端接收一个分离的EntityObject,并且能够告诉该实体更改了哪些属性和哪些关系,并将其与上下文中的内容进行比较。 当然,如果这个实体是一个新实体或其中一个关系被添加/删除/修改,它也应该认识到并采取相应行动。
我已经能够识别实体的关系是否是新的,但似乎无法正确添加。 - 我尝试的每一种方法都会得到一个不同的例外。
以下是我用来更新分离对象的方法:
public static void AttachUpdated(this ObjectContext context, EntityObject objectDetached)
{
if (objectDetached.EntityState == EntityState.Detached)
{
object currentEntityInDb = null;
if (context.TryGetObjectByKey(objectDetached.EntityKey, out currentEntityInDb))
{
context.ApplyPropertyChanges(objectDetached.EntityKey.EntitySetName, objectDetached);
//Apply property changes to all referenced entities in context
context.ApplyReferencePropertyChanges((IEntityWithRelationships)objectDetached,
(IEntityWithRelationships)currentEntityInDb); //Custom extensor method
}
else
{
//The entity should be added
//?????
}
}
}
这是我用来更新实体关系的方法:
public static void ApplyReferencePropertyChanges(this ObjectContext context,
IEntityWithRelationships newEntity,
IEntityWithRelationships oldEntity)
{
foreach (var oldRelatedEnd in oldEntity.RelationshipManager.GetAllRelatedEnds())
{
var oldRef = oldRelatedEnd as EntityReference;
if (oldRef != null)
{
// this related end is a reference not a collection
var newRef = newEntity.RelationshipManager.GetRelatedEnd(oldRef.RelationshipName, oldRef.TargetRoleName) as EntityReference;
if (newRef.EntityKey != null)
{
oldRef.EntityKey = newRef.EntityKey;
}
else
{
//When oldRed is a 1:Many relationship
//newRef is an EntityReference<TEntity> object
EntityObject entity = newRef.GetType().GetProperty("Value").GetValue(newRef, null) as EntityObject;
oldRef.EntityKey = entity.EntityKey;
}
}
else
{
IRelatedEnd newRelatedEnd = newEntity.RelationshipManager.GetRelatedEnd(oldRelatedEnd.RelationshipName, oldRelatedEnd.TargetRoleName);
foreach (IEntityWithRelationships e in newRelatedEnd)
{
if (!oldRelatedEnd.Contains((e as IEntityWithKey).EntityKey))
{
//this is a new relation and it needs to be added.
//???????
}
else
{
//Find out if relation was modified - and update it if needed
//????????
}
}
IEnumerable entities = oldRelatedEnd as IEnumerable;
}
}
}
应该如何实施?
请帮助:(
答案 0 :(得分:0)
您的ObjectContext来自哪里? (我假设这是您的Entity Framework数据库参考)
这里可能存在两个问题:
首先,我不认为ObjectContext是可序列化的,因此如果您将其发送到客户端然后再将其发送回去,您将收到错误。
其次,如果要在服务器上保留ObjectConext,则默认情况下每个调用服务器对象,而不是每个会话,因此您将尝试将实体与新的ObjectContext关联。
在我们的项目中,我们将实体框架对象映射到数据传输对象,然后通过WCF发送。在下一版本的Entity Framework中,您尝试做的事情可能更容易(可能吗?)。
答案 1 :(得分:0)
我不确定您想要实现的目标 - 如果您想在服务器端保存更改,可以使用ADO .Net Data Services。是这样的吗?
答案 2 :(得分:0)
请参阅Perseus:
Perseus是一个旨在实现的小项目 探索交换图表的方法 WCF Web上的实体框架实体 服务。项目的关键部分 是存储图形的EntityBag 实体以及变更跟踪 信息。这里希望没人会 用它来储存&amp;运输 像美杜莎的脑袋一样讨厌的东西。 ; - )