すべてのデータをロードしなくても、ADO.NET Entity Frameworkの多対多の関係を削除する方法を知っている人はいますか?私の場合は、プロパティSubscriptionsを持つエンティティTopicがあり、単一のサブスクリプションを削除する必要があります。コードmyTopic.Subscriptions.Remove(...)は機能しますが、最初にすべてのサブスクリプションを読み込む必要があります(例: myTopic.Subscriptions.Load() )。たくさんあるので(これはたくさんあります)サブスクリプション
サブスクリプションをAttach()してからRemove()することができます。ここではAdd()を使用せず、単にAttachを使用します。それが真実であるかのように振る舞う。
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
ですから、どの時点でもすべての購読を引っ張っているわけではありません。
これは、最初にデータをロードせずに削除する方法です。これはEF 5で機能します。以前のバージョンについてはわかりません。
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();