Home

Castle Stronghold

OneToOne

The one-to-one implemented by NHibernate is often misunderstood. It is used for classes that share primary keys and useful when you have some kind of Class Table Inheritance.

The primary key of the table which isn't autogenerated must be declared using PrimaryKeyType.Foreign:

using Castle.ActiveRecord;

[ActiveRecord("Customer")]
public class Customer : ActiveRecordBase 
{
    private int custID;
    private string name;
    private CustomerAddress addr;
    
    [PrimaryKey]
    public int CustomerID 
    {
        get { return custID; }
        set { custID = value; }
    }
    
    [OneToOne]
    public CustomerAddress CustomerAddress 
    {
        get { return addr; }
        set { addr = value; }
    }
    
    [Property]
    public string Name 
    {
        get { return name; }
        set { name = value; }
    }
}

[ActiveRecord("CustomerAddress")]
public class CustomerAddress : ActiveRecordBase 
{
    private int custID;
    private string address;
    private Customer cust;

    [PrimaryKey(PrimaryKeyType.Foreign)]
    public int CustomerID 
    {
        get { return custID; }
        set { custID = value; }
    }
    
    [OneToOne]
    public Customer Customer 
    {
        get { return cust; }
        set { cust = value; }
    }
    
    [Property]
    public string Address 
    {
        get { return addr; }
        set { addr = value; }
    }
}

You should read more about it on NHibernate documentation.

More information on the attribute can be found at Attributes article.

Google
Search WWW Search castleproject.org