如果您創建正確的親子協會,你只需要跟蹤插入的演示模型(PM)實體關係:
PM的:
public class Parent
{
[Key]
public int? ParentID { get; set; }
[Include]
[Composition]
[Association("Parent_1-*_Child", "ParentID", "ParentID", IsForeignKey = false)]
public IEnumerable<Child> Children { get; set; }
}
public class Child
{
[Key]
public int? ChildID { get; set; }
[Include]
[Association("Parent_1-*_Child", "ParentID", "ParentID", IsForeignKey = true)]
public Parent Parent { get; set; }
}
請務必使用[組合]強制WCF RIA調用DomainService上的InsertChild方法。
的Silverlight:
...
public Child NewChild(Parent parent)
{
return new Child
{
ParentID = parent.ParentID,
Parent = parent,
};
}
...
public void SubmitChanges()
{
DomainContext.SubmitChanges(SaveComplete, null);
}
...
如果家長是不是新的,它有一個PARENTID。如果它是新的,則父ID將爲空。通過將Child.Parent設置爲新Parent的引用,RIA會了解您嘗試執行的操作,並在發送給服務器之後保留引用。
的DomainService在服務器上:
[EnableClientAccess]
public class FamilyDomainService : DomainService
{
private readonly IDictionary<object, EntityObject> _insertedObjectMap;
public void InsertParent(Parent parent)
{
ParentEntity parentEntity = new ParentEntity();
ObjectContext.AddToParents(parentEntity);
_insertedObjectMap[parent] = parentEntity;
ChangeSet.Associate(parent, parentEntity, (p, e) => p.ParentID = e.ParentID;
}
public void InsertChild(Child child)
{
var childEntity = new ChildEntity();
if (child.ParentID.HasValue) // Used when the Parent already exists, but the Child is new
{
childEntity.ParentID = child.ParentID.GetValueOrDefault();
ObjectContext.AddToChildren(childEntity);
}
else // Used when the Parent and Child are inserted on the same request
{
ParentEntity parentEntity;
if (child.Parent != null && _insertedObjectMap.TryGetValue(child.Parent, out parentEntity))
{
parentEntity.Children.Add(childEntity);
ChangeSet.Associate(child, childEntity, (c, e) => c.ParentID = e.Parent.ParentID);
}
else
{
throw new Exception("Unable to insert Child: ParentID is null and the parent Parent cannot be found");
}
}
_insertedObjectMap[child] = childEntity;
ChangeSet.Associate(child, childEntity, (c, e) => c.ChildID = e.ChildID);
}
protected override bool PersistChangeSet()
{
ObjectContext.SaveChanges();
_insertedObjectMap.Clear();
return true;
}
}
兩個重要的部分在這裏。首先,'_insertedObjectMap'存儲新插入的沒有設置ID的實體之間的關係。由於您在交易和單個DB調用中執行此操作,因此只會在插入所有實體後才設置ID。通過存儲關係,Child PM可以使用數據庫找到Parent PM的實體版本。 Child實體被添加到Parent實體的Children集合中,LINQToSQL或LINQToEnityFramework應該爲您處理外鍵。
第二部分是在事務提交後關聯更改。在提交父項和子項的情況下,您必須記得在子項上設置ParentID外鍵。
我從ChangeSet.Associate()信息是從哪裏來的:http://blogs.msdn.com/deepm/archive/2009/11/20/wcf-ria-services-presentation-model-explained.aspx
這就是答案,據我所知道的,所以謝謝你的張貼。我想我在研究這件事時偶然發現了一些類似的東西,但我認爲問題在於,實際上我正在處理的是比單純的父母/子女關係更復雜的對象圖,我不認爲這是一種解決方案將會擴展以處理這種複雜性。 – nlawalker 2010-05-17 16:14:34