删除对象之间的1对多关系需要在两侧删除

时间:2011-07-19 11:52:19

标签: asp.net vb.net entity-framework ef-code-first

我正在使用Code First EF。我的项目中有以下代码

If String.IsNullOrEmpty(ddlProductionLocation.SelectedValue) Then
    CurrentUser.ProductionLocation = Nothing
Else
    CurrentUser.ProductionLocation = ProductionLocationRepository.Find(DataContext, Integer.Parse(ddlProductionLocation.SelectedValue))
End If

ddlProductionLocation只是下拉列表,CurrentUser是普通的EF对象,ProductionLocationRepository是无聊的类,它为我提供了间接访问数据库(也返回普通的EF对象)。

User和ProductionLocation具有1对n的关系。

在将ProductionLocation设置为空后,这对于删除关系无法正常工作,它仍然包含原始值。它在少数情况下(在调试期间)随机工作。

基于我已经意识到,这个问题是关系的第二部分。我已将代码更改为:

If String.IsNullOrEmpty(ddlProductionLocation.SelectedValue) Then
    If CurrentUser.ProductionLocation IsNot Nothing Then
        CurrentUser.ProductionLocation.Users.Remove(CurrentUser)
    End If
    CurrentUser.ProductionLocation = Nothing
Else
    CurrentUser.ProductionLocation = ProductionLocationRepository.Find(DataContext, Integer.Parse(ddlProductionLocation.SelectedValue))
End If

我的问题: 这有效,但我相信这不是正确的解决方案。或者是吗?或者我真的必须在所有情况下删除关系的双方?

Thaks

编辑: 最终的解决方案是:

If String.IsNullOrEmpty(ddlProductionLocation.SelectedValue) Then
    Dim pl = CurrentUser.ProductionLocation 'HACK for loading Product Location before setting it
    CurrentUser.ProductionLocation = Nothing
Else
    CurrentUser.ProductionLocation = ProductionLocationRepository.Find(DataContext, Integer.Parse(ddlProductionLocation.SelectedValue))
End If

不好,但有效。

0 个答案:

没有答案
相关问题