如何在不加载所有数据的情况下删除实体框架中的多对多关系

Emi*_*mil 19 ado.net many-to-many entity-framework

有谁知道如何删除ADO.NET实体框架中的多对多关系,而无需加载所有数据?在我的情况下,我有一个实体主题有一个属性订阅,我需要删除一个订阅.代码myTopic.Subscriptions.Remove(...)有效,但我需要先加载所有订阅(例如myTopic.Subscriptions.Load()),我不想这样做,因为有很多(我的意思是很多)订阅

Ste*_*ock 27

您可以Attach()订阅然后删除()它 - 注意,我们这里没有使用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
Run Code Online (Sandbox Code Playgroud)

整个交换,包括从数据库获取原始主题,将这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
Run Code Online (Sandbox Code Playgroud)

因此,它不会在任何时候提取所有订阅.