異常

2012-02-22 71 views
2

每當我這樣做如下:異常

public class MyDto 
{ 
    [Key] 
    public int ID { get; set; } 

    public int ParentID { get; set; } 

    public String Name { get; set; } 
} 

MyDataContext dataContext = new MyDataContext(); 

MyParentDto myParentDto; // <-- Existing parent DTO querried from the server. Has a relation to MyDto on MyDto.ParentID == MyParentDto.ID. 
List<MyDto> myDtos = new List<MyDto>(); 

myDtos.Add(new MyDto 
    { 
     Name = "First MyDto!" 
    }); 

myDtos.Add(new MyDto 
    { 
     Name = "Second MyDto!" 
    }); 

// Some time later. 


foreach (var myDto in myDtos) 
{ 
    myDto.ParentID = myParentDto.ID; 
    dataContext.MyDtos.Add(myDto); 
} 

dataContext.SubmitChanges(OnMyCallback) 

我得到下面的模糊例外,但我的數據提交就好:

System.ServiceModel.DomainServices.Client.DomainOperationException: Submit operation failed. An entity with the same identity already exists in this EntitySet. 

堆棧跟蹤結束與:

System.ServiceModel.DomainServices.Client.EntitySet.AddToCache(Entity entity) 
System.ServiceModel.DomainServices.Client.Entity.AcceptChanges() 

兩個MyDto情況下被設置爲之後將它們添加到dataContextNew之前。如果我將添加的MyDto實例的數量減少爲1,則不會出現錯誤。如果我在這兩個補充之間呼叫SubmitChanges。同樣,這兩個MyDto實例都被添加到數據庫中,但是客戶端崩潰了Exception。到底是怎麼回事?謝謝。

編輯:

// On the server 

[Insert] 
public void InsertMyDto(MyDto a_myDto) // <- Yes I prefix. :p 
{ 
    try 
    { 
     MyEntity myEntity = new MyDto 
     { 
      ParentID = a_myDto.ParentID, 
      Name = a_myDto.Name 
     } 

     ObjectContext.MyEntities.AddObject(myEntity); 
     ObjectContext.SaveChanges(); 

    } 
    catch (Exception) 
    { 
     throw; // <- Never hits this spot. 
    } 
} 

// Call back 

public void OnMyCallback(SubmitOperation a_submitOperation) 
{ 
     if (a_submitOperation.HasError) 
      throw a_submitOperation.Error; // <- It doesn't matter if I have this or not, the client crashes anyway. 

     // Other stuff that is not hit because it throws the exception above. 
} 
+0

「ID」是一個自動增量列嗎?如果是這樣,EF知道嗎? – hvd 2012-02-22 19:47:32

+0

你可以發佈你的提交更改代碼嗎? (加上回調行動) – sebagomez 2012-02-22 19:52:59

+0

@ hvd,是的,是的。 – Jordan 2012-02-22 19:55:25

回答

2

我發現我的問題的解決方案是將實體保存時將ID保存回dto。像這樣:

[Insert] 
public void InsertMyDto(MyDto a_myDto) // <- Yes I prefix. :p 
{ 
    try 
    { 
     MyEntity myEntity = new MyDto 
     { 
      ParentID = a_myDto.ParentID, 
      Name = a_myDto.Name 
     } 

     ObjectContext.MyEntities.AddObject(myEntity); 
     ObjectContext.SaveChanges(); 

     a_myDto.ID = myEntity.ID; // <- Solution 

    } 
    catch (Exception) 
    { 
     throw; // <- Never hits this spot. 
    } 
} 
1

你試過設置,而不是它的ID父?

foreach (var myDto in myDtos) 
{ 
    myDto.Parent = myParentDto; 
} //Assuming myParentDto is already in the context, if not add it first 

編輯:我瞎猜在這裏,但你可以檢查異常發生前右對象的HashCode?您也可以嘗試覆蓋GetHashCode()方法以每次都隨機返回一些內容,只是爲了測試這些是異常中涉及的確切實體。

+0

是的,我考慮過這一點,但我不相信父母關係是問題。我會盡力而爲。麻煩似乎是它回來並試圖緩存DTO的時候;考慮堆棧跟蹤。 – Jordan 2012-02-23 15:39:47

+0

nope。同樣的問題。 :( – Jordan 2012-02-23 20:44:51