Given the entities: Topics
and Subscriptions
with many-to-many relationship and the corresponding tables: Topics
, Subscriptions
, TopicsSubscriptions
, I want to delete only one row from TopicsSubscriptions
using EF, but without loading any extra data (except of maybe only 1 topic and 1 subscription).
In the end I want EF to generate similar SQL to this:
exec sp_executesql N'delete [dbo].[TopicSubscriptions]
where (([TopicId] = @0) and ([SubscriptionId] = @1))',N'@0 int,@1 int',@0=1,@1=2
I have LazyLoading
set to false
.
I thought I could take the answer from here: How to delete many-to-many relationship in Entity Framework without loading all of the data.
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); // !!! This line does not work for me (Attach to ICollection<> ?!?) !!! topic.Subscriptions.Attach(subscription); // Attach it (theObjectContext now 'thinks' it belongs to the topic) topic.Subscriptions.Remove(subscription); // Remove it db.SaveChanges(); // Flush changes
But then I realized there is no Attach
method belonging to ICollection<>
... unless I am missing something.
Idea of attaching only one subscription to a topic sounds good, but I cannot understand how to achieve it.
I am using DbContext
instead of ObjectContext
and Entity Framework 6 but I guess it should not matter.
EDIT: Would be good to find a solution without stored procedures, or direct sql, if possible, since I have to support many database back-ends in my app.
In case I was not clear enough, I don't need to delete the entities, I just need to remove the association between them.