每當我這樣做如下:異常
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
情況下被設置爲之後將它們添加到dataContext
和New
之前。如果我將添加的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.
}
「ID」是一個自動增量列嗎?如果是這樣,EF知道嗎? – hvd 2012-02-22 19:47:32
你可以發佈你的提交更改代碼嗎? (加上回調行動) – sebagomez 2012-02-22 19:52:59
@ hvd,是的,是的。 – Jordan 2012-02-22 19:55:25