【问题标题】:Deleting relationships from detached state从分离状态中删除关系
【发布时间】:2012-02-27 23:02:05
【问题描述】:

我在下午的大部分时间里一直在尝试找到一个好的解决方案,但无济于事。

当我使用实体框架 (EF) 查询数据时,我总是使用 MergeOption.NoTracking,因为我不想使用数据库对象在我的视图中显示。我最终将 EF 生成的 POCO 类映射到视图模型中,这些视图模型具有可爱的小属性,例如必需、显示名称等。当我需要进行更新时,我最终将我的视图模型映射回生成的类由实体框架执行创建或更新操作。

我正在尝试找到一种简单的方法来删除与我的对象的关系,但由于它们是分离的,所以我无法找到一种方法来做到这一点。我看到有人建议附加和删除该对象,但由于我的对象已分离,因此无法正常工作(它会导致消息 Attach is not a valid operation when the source object associated with this related end is in an added, deleted, or detached state. Objects loaded using the NoTracking merge option are always detached. 出现异常)。

这是我当前代码的示例:

    //Find the records that need to be deleted.
    var productVersionsToDelete = (from pv in existingDownloadFile.ProductVersions
                                  where !selectedVersions.Contains(pv.Id)
                                  select pv).ToList();

    foreach (var productVersionToDelete in productVersionsToDelete) {
        existingDownloadFile.ProductVersions.Attach(productVersionToDelete);
        existingDownloadFile.ProductVersions.Remove(productVersionToDelete);
    }

有没有人建议从分离状态中删除对象?

【问题讨论】:

    标签: c# entity-framework-4


    【解决方案1】:

    问题是,一旦调用 attach,整个对象图就会被附加。给定一个名为 contextDbContext,一个应该工作的示例如下:

    // Attach the download file to the context set (this will attach all ProductVersions
    context.DownloadFiles.Attach(existingDownloadFile);
    
    //Find the records that need to be deleted.
    var productVersionsToDelete = (from pv in existingDownloadFile.ProductVersions
                                  where !selectedVersions.Contains(pv.Id)
                                  select pv).ToList();
    
    foreach (var productVersionToDelete in productVersionsToDelete)
        existingDownloadFile.ProductVersions.Remove(productVersionToDelete);
    
    context.SaveChanges();
    

    这假定 DownloadFiles 是您的 DbContext 上的属性名称,它公开与 existingDownloadFile 类型匹配的实体。

    您得到的例外是因为一旦您附加了ProductVersion,它就会附加相关的existingDownloadFile,而该existingDownloadFile 只能附加一次。

    【讨论】:

    • 感谢您的帮助,成功了。一个问题。在我的情况下,existingDownloadFile 没有附加。我所有的对象都处于分离状态。发生错误仅仅是因为需要附加关系链中的顶级对象吗?我仍然不确定我是否已经弄清楚为什么会发生错误。
    • 我相信当您附加第一个productVersionToDelete 时,它有一个对existingDownloadFile 的引用,这也会导致它被附加。下一次调用 attach 时,它试图再次附加 existingDownloadFile,但第一次是附加的,所以发生了错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 2021-05-16
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 2016-11-27
    • 2011-01-01
    相关资源
    最近更新 更多