2012-08-17 19 views
0

我有兩張表格,其中我保存了人物之間的關係。我想要的層次結構,所以我的兩個表是:與自我跟蹤實體具有相同密鑰的兩個實體的EF 4.0錯誤

Persons 
----------- 
IDPerson 
Name 



PersonRelation 
----------------- 
IDPersonRelation 
IDPerson 
IDRootPerson 
IDParentPerson 
Left 
Right 
Deep 

IDPerson是一個自動數字和IDRelation是其他自動數字。

然後,在SQL Server,創建3間的關係:

1)PersonRelation.IDPerson = Persons.IDPerson 2)PersonRelation.IDPersonRoot = Persons.IDPerson 3)PersonRelation.IDPersonParent = Persons.IDPerson

第一個關係,我想知道層次結構樹的實際節點(名稱,電話...)的人的信息

與第二個關係我想要的信息的根一種屬於實際節點的樹。

隨着三個真正的我想父母。

那麼,這是有一個想法,最重要的是,我有兩個關係有三個表,因爲是問題的原因。層次結構是這樣的。

好了,現在用EF我用下面的代碼,看看,如果這個工程:

Persons person1 = new Persons(); 
person1.Name= "person01"; 

PersonRelation1 relation1 = new PersonRelations(); 
relation1.Left = 1; 
relation.Right = 2; 
relation.Deep = 0; 
person1.PersonRelations.Add(relation1); 

//I am using self tracking entities, so I apply changes 
miContext.ApplyChanges<Persons>("Persons", person1); 
miContext.SaveChanges(); 

這工作得很好,但如果我嘗試添加兩個人與他們的關係,那麼我的問題saveChanges,它表示存在兩個具有相同鍵的實體。代碼如下:

Persons person1 = new Persons(); 
person1.Name= "person01"; 

PersonRelation1 relation1 = new PersonRelations(); 
relation1.Left = 1; 
relation.Right = 2; 
relation.Deep = 0; 
person1.PersonRelations.Add(relation1); 


Persons person2 = new Persons(); 
person2.Name= "person02"; 

PersonRelation2 relation2 = new PersonRelations(); 
relation2.Left = 1; 
relation2.Right = 2; 
relation2.Deep = 0; 
person2.PersonRelations.Add(relation2); 

//I am using self tracking entities, so I aply changes 
miContext.ApplyChanges<Persons>("Persons", person1); 
miContext.ApplyChanges<Persons>("Persons", person2); 
miContext.SaveChanges(); 

爲什麼有一個註冊表工作,當我嘗試添加兩個或多個我有問題?因爲我正在嘗試兩個添加兩個diferents實體。

非常感謝。

回答

0

好了,問題是,我需要PersonRelation添加到Person實體的三個集合,所以我需要做到以下幾點:

Persons person1 = new Persons(); 
person1.Name= "person01"; 

PersonRelation1 relation1 = new PersonRelations(); 
relation1.Left = 1; 
relation.Right = 2; 
relation.Deep = 0; 
person1.PersonRelations.Add(relation1); 
person1.PersonRelations1.Add(relation1); 
person1.PersonRelations2.Add(relation1); 


Persons person2 = new Persons(); 
person2.Name= "person02"; 

PersonRelation2 relation2 = new PersonRelations(); 
relation2.Left = 1; 
relation2.Right = 2; 
relation2.Deep = 0; 
person2.PersonRelations.Add(relation2); 
person2.PersonRelations1.Add(relation2); 
person2.PersonRelations2.Add(relation2); 

miContext.ApplyChanges<Persons>("Persons", person1); 
miContext.ApplyChanges<Persons>("Persons", person2); 
miContext.SaveChanges(); 

我的意思是,這個人實體有3個集,每個關係一個,並且需要將PersonRelation實體添加到三個集合。

謝謝。

相關問題