3

我正在尝试以以下方式删除对一对多关系中实体的引用,但是当我尝试将对象“o”附加到我的 DbContext 时收到错误消息。错误是:

“不允许添加与处于已删除状态的实体的关系。”

我还尝试了以下方法来代替设置 EntityState:

 _db.OrganizationMetrics.Remove(om)

删除它的正确方法是什么?

<HttpPost()>
Function Edit(ByVal ovm As OrganizationViewModel)

    Dim o As Organization


    o = AutoMapper.Mapper.Map(Of OrganizationViewModel, Organization)(ovm)

    For Each om In o.OrganizationMetrics
        _db.OrganizationMetrics.Attach(om)

        If om.Value = "removeMe" Then
            _db.Entry(om).State = EntityState.Deleted
        ElseIf om.Id = 0 Then
            _db.Entry(om).State = EntityState.Added
        Else
            _db.Entry(om).State = EntityState.Modified
        End If
    Next

    _db.Organizations.Attach(o) 'Error is thrown here

    If (ModelState.IsValid) Then

        _db.Entry(o).State = EntityState.Modified
        _db.SaveChanges()

        Return RedirectToAction("Index")
    Else

        Return View(ovm)
    End If

End Function

更新:

这是我现在运行的代码。关键是不要将子实体从视图模型映射回父实体模型,以便我可以单独处理它们。

    <HttpPost()>
    Function Edit(ByVal ovm As OrganizationViewModel)

        Dim o As Organization

        o = AutoMapper.Mapper.Map(Of OrganizationViewModel, Organization)(ovm) //The Automapper code ignores the OrganizationMetrics members
        _db.Organizations.Attach(o)

        For Each om In ovm.OrganizationMetrics
            _db.OrganizationMetrics.Attach(om)

            If om.Value = "removeMe" Then
                _db.Entry(om).State = EntityState.Deleted
            ElseIf om.Id = 0 Then
                _db.Entry(om).State = EntityState.Added
            Else
                _db.Entry(om).State = EntityState.Modified
            End If
        Next


        If (ModelState.IsValid) Then

            _db.Entry(o).State = EntityState.Modified
            _db.SaveChanges()

            Return RedirectToAction("Index")
        Else

            Return View(ovm)
        End If

    End Function
4

1 回答 1

3

当您将 o 附加到 时_db.Organizations.Attach(o),它会遍历其所有子级并发现其中一些已被删除。当它尝试附加它们时,您会收到所显示的错误。这很有意义。

退后一步,弄清楚你想要做什么。删除某些内容的最简单方法是获取它然后删除它。就像是:

context.DeleteObject(context.MyEntity.Single(r => r.Id == myId));

如果需要,您可以MyEntity仅使用其键模拟对象,然后删除该对象,它也可以正常工作并为您保存选择查询。

于 2011-05-25T19:59:32.743 回答