Fluent NHibernate Mapping not on PK Field

2019-06-14 12:18发布

问题:

I have the following tables and cannot edit their structure...

Person
------
Id PK
Code
Name

Order
-----
Id PK
Person_Code
OrderDetails

Now in my Person class I want to have a list of Orders for that person, but I'm not entirely sure how to go about setting up the mapping in fluent nhibernate to match on the Code column rather than the ID. There is no foreign key constraint and I am unable to change the database to use the keys. Something like this is what I require, but can;t seem to figure out the mapping.

public class Person
{
    public virtual int Id { get; set; }
    public virtual string Code { get; set; }
    public virtual IList<Order> Orders { get; private set; }
}

public class Order
{
    public virtual int Id { get; set; }
    public virtual string OrderDetails { get; set; }
    public virtual Person Owner { get; set; }
}

回答1:

You define your column with the KeyColumn method. It should work regardless of existence of a foreign key constraint.

class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {
        HasMany(p => p.Order)
            .KeyColumn("Person_Code")
            .PropertyRef("Code");
    }
}

PropertyRef method is available from rev 614 so you may need to update the fluent nhibernate version.