3

I'm trying to learn NHibernate 3.2 built-in mapping by code api (NOT Fluent NHibernate). Can you help me to map a one-to-one(or zero) relationship between these entities please?

NOTE: I googled the question, also I search the SOF, all examples are using Fluent API or XML; I'm trying to use built-in mapping API in NHibernate 3.2

public class Person { 
    public virtual int Id { get; set; }  
    public virtual string FirstName { get; set; } 
    public virtual string LastName { get; set; } 

    // can be null 
    public virtual Address Address { get; set; }
} 
 
public class Address { 
    public virtual int Id { get; set; } 
    public virtual string Line1 { get; set; } 
    public virtual string Line2 { get; set; } 
    public virtual string City { get; set; }

    // can not be null
    public virtual Person Person { get; set; } 
}

Primary key strategy is here:

Id( 
    t => t.Id, 
    t => { 
        t.Generator(Generators.HighLow, g => g.Params(new { max_low = 100 })); 
        t.Column(typeof(TEntity).Name + "Id"); 
    });
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
amiry jd
  • 27,021
  • 30
  • 116
  • 215
  • 1
    Posting the XML you want may help us understand your question a bit more. – Rippo Mar 05 '12 at 08:44
  • Thanks. I'm just new to NH and I dont know about xml or Fluent. I update the Q and add primary key strategy there. thanks in advanced – amiry jd Mar 05 '12 at 09:00

1 Answers1

5

Depending on what you ACTUALLY want- a one-to-one map or a many-to-one map may answer your question. Please see this link for one-to-one if you need a truly unique bi-directional constraint: http://notherdev.blogspot.com/2012/01/mapping-by-code-onetoone.html

One-to-ones are normally a bad strategy because it makes sense to just put the columns all on one table in almost all cases, and separate them via a component mapping if you need them to be separate entities in your domain. The typical way to separate them in the domain AND the data models is to use a many-to-one with a unique constraint tying back up to the parent and this is a common pattern.

For tips and hints on general 3.2 mappings, this resource has been a ton of help for me: http://notherdev.blogspot.com/2012/02/nhibernates-mapping-by-code-summary.html

Fourth
  • 9,163
  • 1
  • 23
  • 28
  • `One-to-ones are normally a bad strategy because...` thanks a lot; I get a good idea from your answer. Answer voted up and accepted. Regards. – amiry jd Mar 05 '12 at 18:55