6

I am new to fluent nhibernate and nhibernate. I want to write a fluent nhibernate autopersistence convention to handle creating the many to many mappings for my entities.

This is what I have right now:

using System;
using FluentNHibernate.Conventions;
using FluentNHibernate.Mapping;

namespace Namespace
{
    public class HasManyToManyConvention : IHasManyToManyConvention
    {
        public bool Accept(IManyToManyPart target) {
            return true;
        }

        public void Apply(IManyToManyPart target) {
            var parentName = target.EntityType.Name;
            var childName = target.ChildType.Name;
            const string tableNameFmt = "{0}To{1}";
            const string keyColumnFmt = "{0}Fk";
            string tableName;

            if (parentName.CompareTo(childName) < 0) {
                tableName = String.Format(tableNameFmt, parentName, childName);
            }
            else {
                tableName = String.Format(tableNameFmt, childName, parentName);
            }

            target.WithChildKeyColumn(String.Format(keyColumnFmt, childName));
            target.WithParentKeyColumn(String.Format(keyColumnFmt, parentName));
            target.WithTableName(tableName);
            target.Cascade.All();
        }
    }
}

It seems to work, but I feel that there is a better way to do this.

Now my questions:

  1. Do you have a better way to do this?
  2. Do you usually want the Cascade behavior here?
  3. Do I need to worry about something besides making sure both sides of this association end up with the same table name?
kuhlmancer
  • 85
  • 1
  • 8

0 Answers0