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

Asp.net 删除对象之间的1对多关系需要在两侧删除,asp.net,vb.net,entity-framework,ef-code-first,Asp.net,Vb.net,Entity Framework,Ef Code First,我使用的是代码优先。我的项目中有以下代码 If String.IsNullOrEmpty(ddlProductionLocation.SelectedValue) Then CurrentUser.ProductionLocation = Nothing Else CurrentUser.ProductionLocation = ProductionLocationRepository.Find(DataContext, Integer.Parse(ddlProductionLo

我使用的是代码优先。我的项目中有以下代码

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对象)

用户和ProductionLocation具有1对n关系

这对于删除关系不起作用,因为在将ProductionLocation设置为nothing后,它仍然包含原始值。它在少数情况下(在调试等过程中)是随机工作的

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

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
我的问题: 这是可行的,但我认为这不是正确的解决方案。还是这样?或者我真的必须在任何情况下都消除关系的双方吗

塔克斯

编辑: 最终解决办法是:

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

不太好,但很有效。

“…将ProductionLocation设置为nothing后,它仍然包含原始值…”:这是什么意思?在数据库中,调用
SaveChanges
?@Slauma后,这意味着在调试时,我会在将值设置为nothing后立即检查该值,并且可以看到它仍然包含原始值,而不是nothing。当然,保存更改后的数据库也没有更改。哦,但是
User.ProductionLocation
的属性getter或setter中肯定发生了某些事情。我相信,这不仅仅是一个简单的赋值或检索值。您能用
ProductionLocation
属性显示
User
类吗?问题一定出在EF本身。好吧,只要我现在有函数代码,我就不必在意,但我不喜欢:(.Property是用默认的geter seter声明的(当然,这被EF生成的代理所覆盖)。无论如何,谢谢。啊,代理!因为您使用的是延迟加载,所以问题可能与此处相同:。这也解释了为什么它有时在调试期间工作:可能在您观看
CurrentUser.ProductionLocation
的内容时总是工作(从而触发延迟加载属性)在此情况下,更改跟踪检测到导航属性已更改(从某物更改为无),并将此更改保存到数据库。