vsevolod
vsevolod

Reputation: 155

NHibernate many-to-many inserts null id with hilo generator

I have 3 tables: User, Department and UserDepartment. User can be associated with multiple departments and department can be associated with multiple users. I use many-to-many fluent mapping on both sides like this:

For Department

HasManyToMany(x => x.Users)
    .Table("UserDepartment")
    .ParentKeyColumn("DepartmentId")
    .ChildKeyColumn("UserId")
    .AsSet()
    .Cascade.All();

For User

HasManyToMany(x => x.Departments)
    .Table("UserDepartment")
    .ParentKeyColumn("UserId")
    .ChildKeyColumn("DepartmentId")
    .AsBag()
    .Inverse()
    .Cascade.None();

All tables use HiLo Id generator and almost similar mapping, like this:

Id(p => p.Id).GeneratedBy.HiLo("HiLo", "NextHi", "32", "ForTable = 'UserDepartment'");

When I try to add some users to department nhiberante fails with an error:

could not execute batch command.[SQL: SQL not available]. And inner exception: Cannot insert the value NULL into column 'Id', table 'test.dbo.UserDepartment'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated.

I have the same HiLo generator working with other tables, so I'm pretty sure it doesn't cause this failure.

Can someone shed some light on this problem? I can recall having problem with null Id insert in the past and it was solved by using inverse mapping on collection, but I cannot use inverse on both sides, so I need another solution.

Upvotes: 0

Views: 382

Answers (1)

vsevolod
vsevolod

Reputation: 155

Finally I have found the solution. There are two ways:

  1. Remove synthetic ID from table and use composite ID instead.
  2. Use XML mapping to specify idbag behaviour.

as expained in: NHibernate, HiLo and many-to-many association

Upvotes: 1

Related Questions