Joris Molnar
Joris Molnar

Reputation: 130

NHibernate is ignoring ForeignKey property

Situation

The project I am working on at this moment uses NHibernate with Fluent NHibernate.
The Oracle database already exists and can't/shouldn't be changed.

The problem I am having is that Fluent NHibernate seems to ignore the ForeignKey property/method in the following code sample.

Table("PERSON_PACKET");
Id(x => x.Id, "ID").GeneratedBy.UuidHex("N");

// Some Map(...) methods

References(x => x.Packet)
    .Column("PKT_IDENTIFICATION")
    .ForeignKey("IDENTIFICATION")
    .Cascade.None()
    .Fetch.Select()
    .Not.LazyLoad();

Can someone explain what is happening here?

How I discoved this

This part of the database has the following structure:

ERD

All three these entities are actually Views and not Tables, but the tables behind it are similar.

The PACKET view has two similar fields. One called IDENTIFICATION which is a number, and one called ID that is the IDENTIFICATION with some other data concatenated and is a varchar.
PACKET_PERSON has the column PKT_IDENTIFICATION that has the same concatenated format as PACKET.ID (so not PACKET.IDENTIFICATION)

The weird thing is the above mapping worked, even though the wrong column was in the ForeignKey method. This mapping has worked since 2014.
I then tried changing the ForeignKey method to ForeignKey("ID") which worked too.

Finally I changed the method to ForeignKey("JUST_SOMETHING_THAT_IS_NO_COLUMN") and things kept working.

What is happening here?

Upvotes: 0

Views: 362

Answers (1)

David Osborne
David Osborne

Reputation: 6781

I think that method is there for schema generation. I think it equates to this part of the NH XML mapping.

From the documentation:

...specifies the name of the foreign key constraint generated for an association, use it on <one-to-one>, <many-to-one>, <key>, and <many-to-many> mapping elements.

This is why it's not having any observable effect. You would only see a foreign key constraint named JUST_SOMETHING_THAT_IS_NO_COLUMN if you generated a database from your mapping files.

If you're not going to generate a schema, your mapping could become:

References(x => x.Packet)
    .Column("PKT_IDENTIFICATION")
    .Cascade.None()
    .Fetch.Select()
    .Not.LazyLoad();

With no ill effect.

Upvotes: 2

Related Questions