Reputation: 2240
Here is my problem:
Domain: I have following Entities: [Sensor] that can be positioned at [Location]. It is a many-to-many relationship. I break it into two one-to-many to aggregate a [Position] of a [Sensor] at [Location]. Intermediate Entity is [SensorPosition].
Mapping for [SensorPosition] is as follows:
CompositeId().KeyReference(sp => sp.Sensor).KeyReference(sp => sp.Location);
References(sp => sp.Sensor).ForeignKey().Not.Nullable();
References(sp => sp.Location).ForeignKey().Not.Nullable();
Component(sp => sp.Position, p =>
{
p.Map(pos => pos.X);
p.Map(pos => pos.Y);
p.Map(pos => pos.Z);
});
I'm using a CompositeId() to enforce constraint of only one [Sensor] at one [Location]. (Same [Sensor] can be at different [Location]s, it is a business logic twist)
My question is: Can I add a generated primary key (Id) to this? I've tried it, but with CompositeId() in the mapping it is not being generated. Or is there any other way to enforce this constraint fluently?
Upvotes: 2
Views: 941
Reputation: 12680
To generate composite primary key IDs you need to establish a bi-directional relationship between the foreign key properties and each entity referenced in the composite ID. When you create an instance of SensorPosition, assign each References property to the appropriate entities that make up the key and NHibernate will use their Id values for the SensorPosition key.
In the long run, it's much simpler (and generally recommended) to use a "surrogate" key instead of a composite key in NHibernate.
Upvotes: 1
Reputation: 4072
I would avoid using composite primary keys. Uniquenes can be enforced by this mapping:
References(sp => sp.Sensor).UniqueKey("KeyName");
References(sp => sp.Location).UniqueKey("KeyName");
For more details see this question.
Upvotes: 1