Search code examples
c#sql-servernhibernatefluent-nhibernate

How to delete records in JOIN table (many-to-many) using NHibernate without knowing table name


I'm trying to delete all records for mapped tables in NHibernate as part of the setup for a functional test through the browser. From other questions, I am getting the class meta data for all of my mapped classes, which gets me the table name. From there I'm executing a SQL delete statements against the database. This is working well, except I have one join table that isn't directly mapped, but is mapped as part of a many-to-many relationship.

It's this table, the many-to-many relationship, that I need to clear out, and I can't figure out how to do this. While I can't post the exact mappings, here is a close approximation of the database schema:

BlogPosts
---------
BlogPostId (Primary Key)

Tags
----
TagId (Primary Key)

BlogPostTags
------------
BlogPostId (Foreign Key)
TagId (Foreign Key)

And the close approximation of the Fluent NHibernate mapping:

public class BlogPostMap : ClassMap<BlogPost>
{
    public BlogPostMap()
    {
        // ...

        HasManyToMany(post => post.Tags)
            .Table("BlogPostTags")
            .ChildKeyColumn("TagId")
            .ParentKeyColumn("BlogPostId")
            .AsSet()
            .Access.CamelCaseField()
            .Cascade.All();
    }
}

How do I delete records in the "BlogPostTags" table without hard coding the table name, and without enabling cascading deletes?


Solution

  • you can get the table name from the configuration

    Configuration config = ...
    var collection = (Collection)config.GetClassMapping(typeof(BlogPost)).GetProperty("Tags").Value;
    var tablename = collection.CollectionTable.GetQualifiedName(Dialect.GetDialect(config.Properties));