Fluent Nhibernate 1.0 - Specify foreign key constraint name between class and joined subclass
Asked Answered
D

3

13

I think this should be simple, but I can't figure out how to do it. Suppose I have the following maps:

public class AnimalMap : ClassMap<Animal> { Id( x => x.Id); }

public class CatMap: SubclassMap<Cat> {
    Extends<AnimalMap>();
    Map(x => x.IsDomestic);
}

Which creates tables as I expect:

Animal
------
Id

Cat
----
AnimalId : FK to Animal (named FK3500ABA0D)
IsDomestic

As noted, the FK gets generated by the db and ends up as FK3500ABA0D. All I want to do is set the name of that constraint, but I can't find how to do it via Fluent NHibernate (or actually even plain NHibernate, for that matter).

So, what am I missing?

Den answered 21/6, 2010 at 12:57 Comment(1)
FNH 1.0 did not have the ability to name FKs. My accepted answer pertains to that version, but later versions should see the answer below.Den
S
1

I don't know if FluentNH supports it, but the XML is simple:

<joined-subclass name="Cat">
  <key column="AnimalId" foreign-key="NameOfTheFK"/>
</joined-subclass>
Setup answered 21/6, 2010 at 18:30 Comment(0)
A
22

Fluent NH does allow this:

public class ReferenceConvention : IReferenceConvention{
     public void Apply(IManyToOneInstance instance) {
          instance.ForeignKey(string.Format("FK_{0}_{1}",
               instance.EntityType.Name,
               instance.Name));
     }
}

You'd also need to implement IHasManyConvention and IHasManyToManyConvention in the same way as above.

Apteral answered 4/4, 2011 at 16:35 Comment(1)
FYI, at the time the question was asked and answer that feature was not in FNH. I've updated the question and left a comment explaining why the accepted answer is not being changed. Thanks for your answer as well!Den
S
1

I don't know if FluentNH supports it, but the XML is simple:

<joined-subclass name="Cat">
  <key column="AnimalId" foreign-key="NameOfTheFK"/>
</joined-subclass>
Setup answered 21/6, 2010 at 18:30 Comment(0)
P
0

I had the same problem, the following works well for me:

public class JoinedSubclassForeignKeyConvention : IJoinedSubclassConvention
{
    public void Apply(IJoinedSubclassInstance instance)
    {
        if (instance.Type.BaseType != null)
            instance.Key.ForeignKey(string.Format("FK_{0}_{1}", instance.EntityType.Name, instance.Type.BaseType.Name));
    }
}

Your foreign key constraint would then be named as FK_Cat_Animal

Pudding answered 4/6, 2013 at 11:30 Comment(1)
Did this work with FNH 1.0 however? Later versions fixed the issue, but this question is about 1.0 specifically.Den

© 2022 - 2024 — McMap. All rights reserved.