James
James

Reputation: 7533

LINQ to Entities delete all entries in many-to-many relationship

I asked a very similar question earlier today, so you might get a bit of deja vu, but I'm afraid I can't work this one out.

I have 3 MySql tables: Students, Classes and StudentsInClasses.

The Entity Framework translates these into two entities Student and Class, each linking to the other with a many-to-many navigation property (e.g. Student.Classes).

But there is no StudentsInClasses entity, so what's the best way to call, using LINQ to Entities, the equivalent of SQL:

DELETE FROM StudentsInClasses;

I definitely want to avoid loading all Classes and their Students. Of course I could do it that way, but that would be horrendous because there are thousands of them and there should be no need.

Many thanks.

Upvotes: 1

Views: 1437

Answers (4)

NoRMO
NoRMO

Reputation: 21

Student.Class.Clear()

It's that simple! Just save changes and the Many-to-Many table will be free of entries for that student.

Upvotes: 2

Wouter de Kort
Wouter de Kort

Reputation: 39898

If you don't like executing a store command like Paperjam suggested you could also create a stored procedure for this. That would nicely map to a static typed function on your ObjectContext.

Upvotes: 1

Boomer
Boomer

Reputation: 1478

First: As far as I know, you can't delete data using EF without first loading that data.

Secondly: you can use ADO or POCO (above EF.4):

 try
        {
            using (testEntities db = new testEntities())
            {                    
                db.ExecuteStoreCommand<returnClass>("DELETE FROM StudentsInClasses;", NULL);
            }
        }
        catch (Exception ex) { _Exceptions.ManageExceptions(ex);}

Upvotes: 3

Massimo Zerbini
Massimo Zerbini

Reputation: 3191

If you have a doubt on your EF mapping, you can check the metadata file. These file are usually present in the directory obj/Debug/edmxResourcesToEmbed of your project. The metadata file yourEntities.msl defines the mapping between objects and tables. In this file you should find that the Students.Classes is mapped on the StudentInClasses table, so removing entries in that list and saving the Students is equal to delete rows on the StudentInClasses table.

Upvotes: 0

Related Questions