删除多对多条目

时间:2014-06-23 09:21:32

标签: vb.net entity-framework

如何删除多对多条目?
我有实体ClientRestaurant以及它们之间的关系表和实体:ClientRestaurant包含以下列:ClientIDRestaurantID,{{1} }。
客户端实体具有导航属性DateOfBill,该列表为ClientRestaurants 当我从ClientRestaurant的{​​{1}}列表中删除条目时:

  

myClient.ClientRestaurants.Remove(myClientRestaurants)

然后尝试Client我收到以下错误:

ClientRestaurants

更新:我将ClientRestaurants表中的列从SQL Server设置为Nullable。现在,如果我这样做:

  

myClient.ClientRestaurants.Remove(myClientRestaurants)   myRestaurant.ClientRestaurants.Remove(myClientRestaurants)

然后SaveChanges它工作正常,我的意思是删除了关系中的条目,但是在DB中仍然是一行Adding a relationship with an entity which is in the deleted state is not allowed.值,因为我有两个SaveChanges列,我只能有一行NULL值。必须有另一种解决方案,但它让我望而却步 任何帮助非常感谢。
这些是向中间表添加和删除记录的函数。

UNIQUE INDEX
  

从上面的描述中将Lucrare视为餐厅,将Tehnician视为客户。

更新:我有这些Subs:

NULL

这样我就会收到错误,它出现在Private Function addTehnicianToLucrare(L As Lucrare, T As Tehnician) As TehnicianLucrare Dim result As TehnicianLucrare = Nothing Dim TL As New TehnicianLucrare TL.Tehnician = T 'T.LucrariTehnician.Add(TL) TL.Lucrare = L 'L.TehnicieniLucrare.Add(TL) If TL IsNot Nothing Then result = TL Return result End Function Private Function removeTehnicianFromLucrare(L As Lucrare, T As Tehnician) As TehnicianLucrare Dim result As TehnicianLucrare = Nothing Dim TL As TehnicianLucrare = Me._ctx.TehnicieniLucrare.Local.Where(Function(p) p.Tehnician Is T And p.Lucrare Is L).SingleOrDefault If TL IsNot Nothing Then Me._ctx.TehnicieniLucrare.Remove(TL) result = TL End If Return result End Function 子退出之后。我已经逐步调试并在每一步之后调用Private Sub list_TehnicieniRaport_DoubleClick(sender As Object, e As EventArgs) Handles list_TehnicieniRaport.DoubleClick Try If Me.list_TehnicieniRaport.SelectedIndex > -1 Then Dim curTeh = TryCast(Me.list_TehnicieniRaport.SelectedItem, TehnicianLucrare) If curTeh IsNot Nothing Then 'setProperty("TehnicieniLucrare", curTeh.Tehnician) moveToDataTable(curTeh.Tehnician) 'ChangeTracker.HasChanges() gives error here End If End If Catch ex As Exception logError(ex) End Try End Sub Public Sub moveToDataTable(ByRef pTehnician As Tehnician) Try setProperty("TehnicieniLucrare", pTehnician) If getProperty("Edit") Then selectEchipa() selectCar() Catch ex As Exception logError(ex) End Try 'ChangeTracker.HasChanges() DOES NOT give error here. End Sub 如果我将moveToDataTable()移动到_ctx.ChangeTracker.HasChanges()子,那么我就不会收到错误,一切正常。我不明白.....

1 个答案:

答案 0 :(得分:1)

摘自你的问题:

having the following columns: ClientID, RestaurantID, DateOfBill.

我感觉这个中间表不是由EF自动生成的,而是您单独定义的单独表。我这背后的主要原因是你要添加DateofBill,这意味着你手动在表格中插入项目。

它可能就像一个中间表,但EF不会那样看。

如果您通过EF设置多对多(即不是由您管理,但是自动生成),则仍会有一个表,但它将隐藏在ORM后面。您的代码段适用于此方案。在这种情况下,您需要删除关系;并且EF将删除内部表格行。 因为该表是描述关系的一部分。

但是如果您的中间表是您自己定义的单独表,那么它就是一个实体;你需要像处理任何其他实体一样处理它。 该表是一个专门定义的表,它与客户端和餐厅有两个关系。

删除ClientRestaurant实体,就像删除任何其他实体一样:

myContext.ClientRestaurantTable.Remove(myEntityToRemove);

不要担心这种关系。它们包含在ClientRestaurant行(ClientID,RestaurantID)中,不会有参考问题。

这里要记住的关键部分是EF为您自动生成的表与您自己设置的中间表之间存在差异(在大多数情况下,只有当您需要该表中的其他列时才会这样做,就像你的DateofBill

一样
相关问题