一次添加多个实体时出现异常

时间:2012-02-22 19:40:28

标签: entity-framework wcf-ria-services

每当我做以下事情时:

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个实例在DetacheddataContext之后被添加到New之前设置为MyDto。如果我将添加的SubmitChanges个实例的数量减少到一个,我就不会收到任何错误。如果我在两个添加之间调用MyDto。同样,两个// 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. } 实例都被添加到数据库中,但是客户端崩溃了Exception。到底是怎么回事?感谢。

编辑:

{{1}}

2 个答案:

答案 0 :(得分: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 :(得分:1)

您是否尝试过设置父级而不是ID?

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

编辑:我在这里做了一个疯狂的猜测,但你可以在异常发生之前检查对象的HashCode吗?你也可以尝试重写GetHashCode()方法,每次只返回一些东西,只是为了测试那些是异常中涉及的确切实体。