Fluent NHibernate: Removing a Relationship Connection From a Many-to-Many

In my last blog post I forgot to show how to disconnect a student from a class but leave both the student and the class records intact. So I quickly ninja’d something together to demonstrate how simple it is to perform this vital function. Here’s my code:

using (ISession db = MSSQLSessionFactory.OpenSession())
{
    // delete connection between student and class
    var student = (from s in db.Query<Student>()
                    where s.Name == "New Student"
                    select s).FirstOrDefault();

    using (db.BeginTransaction())
    {
        foreach (var temp in student.Class)
        {
            if (temp.Name.Trim() == "CSC 300")
            {
                student.Class.Remove(temp);
                break;
            }
        }
                    
        db.Transaction.Commit();
    }
}

First, I queried for the student I wished to disconnect. Then I searched through the list of Classes that the student was assigned to, searching for the one class to disconnect. Once I found the Class (be aware of the Trim() since the Name is a character field) I removed it from the list and committed the transaction. This was all that was necessary to make the StudentClass record delete connecting “New Student” and “CSC 300”.

As Hannibal Smith would say “I love it when a plan comes together!”

Leave a Reply