Question

I have the task of using Fluent NHibernate to map some tables which are used mostly in a legacy application and therefore cannot be changed in structure.

The issue I am having seems to be surrounding the CompositeId mapping which I've used in NHibernate.

Here are the tables:

CREATE TABLE [dbo].[tbl_mtng](
    [mtng_cd] [int] IDENTITY(1,1) NOT NULL,
    ...many other columns...
    [mtng_cancelled] [bit] NOT NULL)

Primary key is defined on mtng_cd.

CREATE TABLE [dbo].[tbl_centre](
    [centre_ID] [int] IDENTITY(1,1) NOT NULL,
    ...many other columns...,
    [centre_name] [nvarchar](100) NOT NULL)

Primary key is defined on centre_ID.

CREATE TABLE [dbo].[tbl_mtng_centre](
     [mtng_cd] [int] NOT NULL,
     [centre_ID] [int] NOT NULL)

Primary key is defined on BOTH mtng_cd and centre_ID. (A composite key)

Here are the Fluent NHibernate mappings:

For my object Centre:

Table("dbo.tbl_centre")
Id(Function(x) x.Id).Column("centre_ID").GeneratedBy().Identity()
HasMany(Of MeetingCentre)(Function(x) x.MeetingCentres).KeyColumn("centre_ID")

For my object Meeting:

Table("dbo.tbl_mtng")
Id(Function(x) x.Id).Column("mtng_cd").GeneratedBy().Identity()
HasMany(Of MeetingCentre)(Function(x) x.Centres).KeyColumn("mtng_cd")

For my object MeetingCentre:

Table("dbo.tbl_mtng_centre")
CompositeId().KeyReference(Function(x) x.Centre, "centre_ID").KeyReference(Function(x) x.Meeting, "mtng_cd")

Here is the issue:

When I create a simple sub to update one of my MeetingCentre objects to have a different Centre (essentially updating part of the primary key), I get the following error:

"Batch update returned unexpected row count from update; actual row count: 0; expected: 1"

I've had this error before with regards to triggers on underlying tables not having NOCOUNT set to ON which interferes with the values returned by SQL server after running NHibernate's updates/inserts, but I don't think that is the issue here as none of the tables have triggers defined.

Is this as simple as NHibernate not wanting to update a composite primary key? Because I can do this in SQL Server, as long as it doesn't violate the uniqueness of the primary key constraint.

If anyone has any solutions or avenues to explore it would be greatly appreciated.

Was it helpful?

Solution

An update on this:

Having not found a way of updating the composite primary key through NHibernate, I decided to look at adding a new one and deleting the existing one. Although at first I had issues with this, I followed the advice of the answer to this question, specifically the Edit where the mappings are defined.

The use of Not.Update() and Not.Insert() on the foreign key references have allowed me to create new rows and delete old ones, thus performing a sort of pseudo update on the foreign key.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top