views:

37

answers:

2

Hi everyone,

I was trying to change a convention so that my IDs follow this simple rule: ProductCode, CustomerCode, OrderCode etc etc.
I've found a simple way to do that adding a convention:

public class PrimaryKeyNameConvention : IIdConvention
        {
            public void Apply(FluentNHibernate.Conventions.Instances.IIdentityInstance instance)
            {
                instance.Column(instance.EntityType.Name + "Code");
            }
        } 

Now I've got what I wanted but it seems that FluentNhibernate refuses to apply the same rule with column referencing my primary keys. EX: my table Customer will have a PK called CustomerCode but my table Order will have a reference column called Customer_Id. I've tried different ways to rename the column Customer_Id in CustomerCode (table Order) but it seems that nothing works properly. The only solution which seems to work is adding a convention like this:

public class ReferenceConvention : IReferenceConvention
        {
            public void Apply(FluentNHibernate.Conventions.Instances.IManyToOneInstance instance)
            {
                instance.Column(instance.Property.PropertyType.Name + "Code");
            }
        }

but now FluentNhibernate creates two columns which reference my primary key: CostumerCode and Customer_Id.

I can't figure out what I am doing wrong. Any help would be apreciated.

Regards,

Alberto

+1  A: 

Take a look at the ForeignKeyConvention base-class.

The ForeignKeyConvention is an amalgamation of several other conventions to provide an easy way to specify the naming scheme for all foreign-keys in your domain. This is particularly useful because not all the foreign-keys are accessible in the same way, depending on where they are; this convention negates need to know about the underlying structure.

James Gregory
Thanks James,it worked.I've applied these two conventions and it worked as expected:PrimaryKeyNameConvention + ForeignKeyConventionAlberto
vandalo
A: 

As James suggested I've now applied these two conventions:

public class PrimaryKeyNameConvention : IIdConvention
{
    public void Apply(FluentNHibernate.Conventions.Instances.IIdentityInstance instance)
    {
        instance.Column(instance.EntityType.Name + "Code");
    }
}

public class CustomForeignKeyConvention : ForeignKeyConvention
{
    protected override string GetKeyName(Member property, Type type)
    {
        if (property == null)
            return (type.Name + "Code");    // many-to-many, one-to-many, join

        return (property.Name + "Code");    // many-to-one
    }
}

and everything works fine.

vandalo
Good to hear. If you wanted a single convention, there's nothing to stop you implementing `IIdConvention` in your `CustomForeignKeyConvention` class instead of on it's own.
James Gregory