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()