【发布时间】: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