3
votes

I'm trying to figure out how to map a component as a primary key in nhibernate and if possible in fluent nhibernate as well.

The component in question is a unique set of 3d coordinates, here's the object:

public class SpaceLocation
{
    public virtual SpaceCoordinate Coordinates { get; set; }
    public virtual SpaceObject AtLocation { get; set; }
}

SpaceCoordinate is a struct defined as follows:

public struct SpaceCoordinate
{
    public int x { get; set; }
    public int y { get; set; }
    public int z { get; set; }
}

In fluent nhibernate to make SpaceCoordinate a componet I would create a mapping class like this:

public class SpaceLocationMap : ClassMapWithGenerator<SpaceLocation>
{
    public SpaceLocationMap()
    {
        References(x => x.AtLocation);
        Component<SpaceCoordinate>(x => x.Coordinates, m =>
        {
            m.Map(x => x.x);
            m.Map(x => x.y);
            m.Map(x => x.z);
        }).Unique();
    }
}

But what I would like to know is how to make the SpaceCoordinate component as a whole the primary key with it's unique constraint. How would I map this in Nhibernate xml, or in a fluent nhibernate classmap?

2

2 Answers

2
votes

I believe that unless you're running on NHibernate trunk, you can't do this. The unique attribute on component wasn't added until after 2.0 was released; so unless there's way around this, I don't think it's possible.

Are you able to map the fields as a composite-id instead?

2
votes

it should be possible now using

public class SpaceLocationMap : ClassMap<SpaceLocation>
{
    public SpaceLocationMap()
    {
        CompositeId(x => x.Coordinates)
            .KeyProperty(x => x.x)
            .KeyProperty(x => x.y)
            .KeyProperty(x => x.z);

        References(x => x.AtLocation);
    }
}