R – Fluent NHibnernate HasManyToMany with Index


I'm trying to map a many-to-many collection with Fluent NHibnernate. My model class has this property:

public virtual IList<Resource> Screenshots
    get { return _screenshots; }
    protected set { _screenshots = value; }

And my fluent mapping is:

HasManyToMany(x => x.Screenshots)
                .AsList(x => x.WithColumn("Index"))

When I run my application, I get the following exception message:

The element 'list' in namespace
'urn:nhibernate-mapping-2.2' has
invalid child element 'many-to-many'
in namespace
'urn:nhibernate-mapping-2.2'. List of
possible elements expected: 'index,
list-index' in namespace

There should be a way to do this. Does anyone know what I am doing wrong?

Best Solution

The current FluentNHibernate syntax for this is as follows:

HasManyToMany(x => x.Screenshots)
    .AsList(i => i.Column("`Index`"));

The index column defaults to Index, but that's a reserved word on SQL Server (and probably other databases too), so you must quote it with back-ticks.

Also, I'd recommend against setting a cascade on this relationship. Consider the following code:


NHibernate will correctly delete rows from the linking table even without a cascade specified. However, if you specify AllDeleteOrphan, then NHibernate will delete the row from the linking table and also delete Resource s. I doubt this is the behavior you want on a many-to-many relationship.