entity-framework – 如何在Entity Framework中删除多对多关系,而无需加载所有数据

有没有人知道如何在ADO.NET实体框架中删除多对多关系,而无需加载所有数据?在我的情况下,我有一个实体主题具有属性订阅,我需要删除单个订阅。代码myTopic.Subscriptions.Remove(…)工作,但我需要加载所有订阅(例如myTopic.Subscriptions.Load()),我不想这样做,因为有很多(我的意思是很多)的订阅。
您可以附加()一个订阅然后Remove()它 – 注意,我们没有使用Add()在这里,只是Attach,所以有效地,我们告诉EF我们知道对象附加在商店,并要求它表现得好像是真的。

var db = new TopicDBEntities();
var topic = db.Topics.FirstOrDefault(x => x.TopicId == 1);

// Get the subscription you want to delete
var subscription = db.Subscriptions.FirstOrDefault(x => x.SubscriptionId == 2);
topic.Subscriptions.Attach(subscription); // Attach it (the ObjectContext now 'thinks' it belongs to the topic)
topic.Subscriptions.Remove(subscription); // Remove it
db.SaveChanges(); // Flush changes

这个整个交换,包括从数据库获取原始主题将这3个查询发送到数据库:

SELECT TOP (1) 
[Extent1].[TopicId] AS [TopicId], 
[Extent1].[Description] AS [Description]
FROM [dbo].[Topic] AS [Extent1]
WHERE 1 = [Extent1].[TopicId]


SELECT TOP (1) 
[Extent1].[SubscriptionId] AS [SubscriptionId], 
[Extent1].[Description] AS [Description]
FROM [dbo].[Subscription] AS [Extent1]
WHERE 2 = [Extent1].[SubscriptionId]


exec sp_executesql N'delete [dbo].[TopicSubscriptions]
where (([TopicId] = @0) and ([SubscriptionId] = @1))',N'@0 int,@1 int',@0=1,@1=2

所以在任何时候都没有拉出所有的订阅。

翻译自:https://stackoverflow.com/questions/757067/how-to-delete-many-to-many-relationship-in-entity-framework-without-loading-all

转载注明原文:entity-framework – 如何在Entity Framework中删除多对多关系,而无需加载所有数据