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

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

问题描述

有谁知道如何删除许多一对多关系ADO.NET实体框架,而无需加载所有的数据?在我来说,我有一个实体的主题有一个属性的订阅,然后我需要删除单个订阅。在code 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.

推荐答案

您可以将()订阅,然后删除()它 - 请注意,我们不使用添加()在这里,只安装,因此有效地我们告诉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天全站免登陆