丹妮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。 –