开发者

FluentNhibernate and References

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 : IReferenceConventi开发者_JS百科on
        {
            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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜