HasMany mapping with non-null key column

I am trying to achieve a HasMany to a column with invalid column.

My mapping is as follows:

 public void Override(AutoMapping<DataExportTable> mapping) { mapping.Table("data_export_tables"); mapping.Id(x => x.Id).Column("data_export_tables_id") .GeneratedBy.Sequence("SQ_DATA_EXPORT_TABLES_ID"); mapping.HasMany(x => x.Columns) .KeyColumn("table_id") .Not.KeyNullable() .Not.KeyUpdate() .Cascade.AllDeleteOrphan(); } 

The code for saving the object is as follows:

 var table = new DataExportTable("table_name"); table.Columns.Add(new DataExportColumn("column_name")); session.Save(table); transaction.Commit(); 

This throws an exception:

NHibernate.Exceptions.GenericADOException: Failed to execute command command. [SQL: SQL is unavailable] ---> Oracle.DataAccess.Client.Orac leException: ORA-01400: cannot insert NULL into ("MYSCHEMA". "DATA_EXPORT_COLUMNS". "TABLE_ID")

Now I read a few posts about this topic, and the common solution seems to be to make the link bidirectional, i.e. add the Table property to the DataExportColumn and set this.
Another hack is to make the foreign key column nullable. This is not what I want. I want NHibernate to insert the identifier directly into the INSERT statement.
According to the log file, NHibernate, of course, knows the ID at the time the INSERT statement is executed:

NHibernate: select SQ_DATA_EXPORT_TABLES_ID.nextval from dual
NHibernate: Command Commands:
command 0: INSERT INTO data_export_tables (NAME, data_export_tables_id) VALUES (: p0 ,: p1) ;: p0 = 'table_name' [Type: String (0)] ,: p1 = 93 [Type: Int32 (0)]

NHibernate: Command Commands:
command 0: INSERT INTO data_export_columns (NAME, data_export_columns_id) VALUES (: p0 ,: p1) ;: p0 = 'column_name' [Type: String (0)] ,: p1 = 1228 [Type: Int32 (0)]

As you can see, NHibernate just skips the table_id column, although the identifier is well known - NHibernate passed it as a parameter to the first insert statement ...

+4
source share
2 answers

So you should set Not.Inverse() as shown in this answer .

 mapping.HasMany(x => x.Columns) .KeyColumn("table_id") .Not.Inverse() .Not.KeyNullable() .Not.KeyUpdate() .Cascade.AllDeleteOrphan(); 

I do not think that a bi-directional relationship is a hacker, and this is usually necessary for requests.

+2
source

You did not indicate which version of NHibernate you are using, but I want to note that this seems to be fixed in version 3.2.0 in accordance with this problem with jira .

If you are stuck with a different version of NHibernate, I would suggest making the ratio bidirectional, as this is a much better use case for NULL-FK, in my opinion.

+2
source

All Articles