"附加"似乎不可用于导航属性集合

时间:2017-01-09 13:00:14

标签: vb.net entity-framework visual-studio-2015 entity-framework-6 ado.net-entity-data-model

查看问题"How to delete many-to-many relationship in Entity Framework without loading all of the data"前2个答案(参见文章)表明存在导航属性集合的附加方法(即, entity1 .Entity2Collection.Attach( entity2 ))。问题是,我有 VS 2015 / EF 6.1.3 (VB和DBContext),并且该方法似乎不存在导航属性集合(或者至少Intellisense没有' t显示它)。我做错了吗?

1 个答案:

答案 0 :(得分:0)

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