如何在不加载所有数据的情况下删除实体框架中的多对多关系 [英] How to delete many-to-many relationship in Entity Framework without loading all of the data

查看:29
本文介绍了如何在不加载所有数据的情况下删除实体框架中的多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does anyone know how to delete many-to-many relationship in ADO.NET Entity Framework without having to load all of the data? In my case I have an entity Topic that has a property Subscriptions and I need to remove a single subscription. The code myTopic.Subscriptions.Remove(...) works but I need to load all subscriptions first (e.g. myTopic.Subscriptions.Load()) and I don't want to do that because there are lots (and I mean lots) of subscriptions.

推荐答案

你可以 Attach() 订阅然后 Remove() 它 - 注意,我们在这里没有使用 Add(),只是 Attach,所以我们很有效告诉 EF 我们知道该对象已附加在存储中,并要求它表现得好像这是真的一样.

You can Attach() a subscription then Remove() it - note, we're not using Add() here, just Attach, so effectively we're telling EF that we know the object is attached in the store, and asking it to behave as if that were true.

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 个查询发送到数据库:

This whole exchange, including getting the original topic from the database sends these 3 queries to the database:

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

所以它不会在任何时候拉出所有订阅.

so it's not pulling all the subscriptions at any point.

这篇关于如何在不加载所有数据的情况下删除实体框架中的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆