如何在不加載所有數據的情況下刪除實體框架中的多對多關係

ado.net entity-framework many-to-many

有誰知道如何刪除ADO.NET實體框架中的多對多關係,而無需加載所有數據?在我的情況下,我有一個實體主題有一個屬性訂閱 ,我需要刪除一個訂閱。代碼myTopic.Subscriptions.Remove(...)有效,但我需要先加載所有訂閱(例如myTopic.Subscriptions.Load() ),我不想這樣做,因為有很多(我的意思是很多)訂閱

一般承認的答案

您可以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

整個交換,包括從數據庫獲取原始主題,將這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

因此,它不會在任何時候提取所有訂閱。


熱門答案

這是在沒有先加載任何數據的情況下刪除的方法。這適用於EF5。對早期版本不確定。

var db = new TopicDBEntities();

var topic = new Topic { TopicId = 1 };
var 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(); 


許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因