简体   繁体   中英

How do you map a component that is also a primary key in NHibernate hbm xml (or in a fluent-nhibernate class map)?

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?

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?

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM