"Attach" doesn't seem to be available for navigation-property collections

53 views Asked by At

A look at the top 2 answers to the question "How to delete many-to-many relationship in Entity Framework without loading all of the data" (see the article) suggests that an Attach method exists for navigation-property collections (i.e., entity1.Entity2Collection.Attach(entity2)). The problem is, I have VS 2015 / EF 6.1.3 (VB and DBContext) and that method doesn't seem to exist for navigation-property collections (or at least Intellisense doesn't show it). Am I doing something wrong?

1

There are 1 answers

0
Robert Gustafson On

Dannie f.'s solution (re-coded for VB) is as follows, assuming a model of TopicDBEntities, and entity-collections of Topic and Subscription:

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