0

一看前2回答這個問題"How to delete many-to-many relationship in Entity Framework without loading all of the data"(見文章)表明,一個附加方法存在導航屬性集合(即,entity1.Entity2Collection.Attach(entity2))。問題是,我有VS 2015/EF 6.1.3(VB和DBContext),並且該方法似乎不存在導航屬性集合(或至少Intellisense不顯示它)。難道我做錯了什麼?「附加」似乎並沒有可用於導航屬性集合

+0

你是對的,沒有這種方法可用於導航屬性集合。你可以看看這篇文章http://stackoverflow.com/questions/39708439/ef-create-remove-relation-from-many-to-many-relations-when-autodetectchangesen,不知道它是否適用於你的情況。 –

+0

Attach不是Entity 6.1.3的一部分,它在以前的某些版本中已被刪除 –

+0

我想出了頁面上的第一個問題,並且我鏈接到的問題不適合EF 6.1.3;第二個答案(dannie.f的答案)是正確的。您必須創建第一個實體的分離實例,將第二個實體添加到其nav-prop集合,附加(未附加)第一個實體,然後執行Remove。 –

回答

0

丹妮F公司的解決方案(重新編碼VB)如下,假設TopicDBEntities和主題的實體的集合和訂閱模型:

Dim db = New TopicDBEntities() 

' Create UNATTACHED instances of the two entities and associate them 
' (In real life, you would have something more sophisticated for the 
' next 2 lines) 
Dim topic = New Topic { .TopicId = 1 } 
Dim subscription = New Subscription { .SubscriptionId = 2} 

topic.Subscriptions.Add(subscription) 

' Attach the topic and subscription as unchanged 
' so that they will not be added to the db 
' but start tracking changes to the entities 
db.Topics.Attach(topic) 

' Remove the subscription 
' EF will know that the subscription should be removed from the topic 
topic.subscriptions.Remove(subscription) 

' commit the changes 
db.SaveChanges()