丹妮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()
你是對的,沒有這種方法可用於導航屬性集合。你可以看看這篇文章http://stackoverflow.com/questions/39708439/ef-create-remove-relation-from-many-to-many-relations-when-autodetectchangesen,不知道它是否適用於你的情況。 –
Attach不是Entity 6.1.3的一部分,它在以前的某些版本中已被刪除 –
我想出了頁面上的第一個問題,並且我鏈接到的問題不適合EF 6.1.3;第二個答案(dannie.f的答案)是正確的。您必須創建第一個實體的分離實例,將第二個實體添加到其nav-prop集合,附加(未附加)第一個實體,然後執行Remove。 –