Silverlight 4.0 Silverlight&x2B;WCF数据服务获取InvalidOperationException:上下文已在跟踪具有相同资源Uri的不同实体

Silverlight 4.0 Silverlight&x2B;WCF数据服务获取InvalidOperationException:上下文已在跟踪具有相同资源Uri的不同实体,silverlight-4.0,wcf,wcf-client,Silverlight 4.0,Wcf,Wcf Client,我试图用一个新的对象替换一个对象,并且得到了提到的异常。我试过几种组合,但都绕不过去 我有一个包含项目的播放列表(这些项目有另一个嵌套对象,但我将省略它以帮助我的问题更清楚。用户可以更改播放列表中的项目 if (playlistChanged) { // remove selectedForRemoval IEnumerable<PlaylistItemViewModel> nonSelectedItems = selectedDisplayTemplates.Wh

我试图用一个新的对象替换一个对象,并且得到了提到的异常。我试过几种组合,但都绕不过去

我有一个包含项目的播放列表(这些项目有另一个嵌套对象,但我将省略它以帮助我的问题更清楚。用户可以更改播放列表中的项目

 if (playlistChanged)
{
    // remove selectedForRemoval
    IEnumerable<PlaylistItemViewModel> nonSelectedItems = selectedDisplayTemplates.Where(pivm => pivm.IsSelectedForRemoval);
    foreach (temViewModel ivm in nonSelectedItems)
    {
        context.DeleteObject(ivm.Model);        
    }

    // clear out and remove old items
    foreach (Item item in playlist.PlaylistItems)
    {
        context.DeleteObject(item);
    }

    playlist.PlaylistItems.Clear();

    // add the selectedItem(s) to the playlist
    // these items can be from the Media, or other tables
    // so are newly created in code on the client           
    foreach (ItemViewModel ivm in selectedItems)
    {
        playlist.Items.Add(ivm.PlaylistItemModel);
        context.AddToItems(ivm.PlaylistItemModel);
    }
    context.BeginSaveChanges(SaveChangesOptions.Batch, new AsyncCallback((iar) =>
    {
        try
        {
            // Callback method for the async request, retrieves the status of the requested action
            DataServiceResponse response = context.EndSaveChanges(iar);
        }
        catch (DataServiceRequestException)
        {
            throw;
        }
    }), context);   
}
if(播放列表已更改)
{
//删除已选择要删除的项目
IEnumerable nonSelectedItems=selectedDisplayTemplates.Where(pivm=>pivm.IsSelectedForRemove);
foreach(非选择性EMS中的TEMVIEW模型ivm)
{
context.DeleteObject(ivm.Model);
}
//清除并移除旧项目
foreach(播放列表中的项目。播放项目)
{
删除对象(项);
}
playlist.playlitems.Clear();
//将选定的编辑项添加到播放列表中
//这些项目可以来自媒体或其他表格
//因此,在客户端的代码中新创建的
foreach(selectedItems中的ItemViewModel ivm)
{
playlist.Items.Add(ivm.PlaylistItemModel);
context.AddToItems(ivm.playlityModel);
}
context.BeginSaveChanges(SaveChangesOptions.Batch,新异步回调((iar)=>
{
尝试
{
//异步请求的回调方法,检索请求操作的状态
DataServiceResponse response=context.EndSaveChanges(iar);
}
捕获(DataServiceRequestException)
{
投掷;
}
}),上下文);
}
感谢您的帮助


编辑:我在Playlist分部类中重写Equals和ToString。在我删除它们之后,它开始工作。

如果您使用与您尝试添加/删除的上下文不同的上下文获取数据,您将获得发布的异常。请处置您获取数据的原始上下文,或者显式调用De您正在调用AddItem/DeleteObject的项目上的tach。

我在Silverlight中重写了播放列表部分类中的Equals和ToString。在我删除它们之后,它开始工作。从现在起,我将使用WCF数据服务避免这种情况。

谢谢,我使用相同的上下文检索播放列表和项目。然后当它们选择另一个项目,我正在客户端的代码中创建一个新项目(我在问题的代码中添加了一条注释)。我想知道为什么上下文会变得混乱。所以你只有一个上下文?除非该项目是分离的或新的,否则你不应该需要/正在调用AddToItems