简体   繁体   中英

Nhibernate One-To-One mapping by code

I am trying to figure out a way to map one to one relationship in nhibernate when referencing column is not a primary key column on second table.

For example consider

Person Table 
   PersonId (pk)
   Name

and

Passport Table 
   PassportId (pk)
   Country
   PersonId

The two tables have one to one relationship on PersonId.

My Nhibernate Model looks like below.

public class Person
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual Passport Passport { get; set; }
}

public class Passport
{
    public virtual int Id { get; set; }
    public virtual string Country { get; set; }
    public virtual Person Person { get; set; }
}

Based on explanation form this article I defined the relationship mapping as follows but it didn't work

PersonMapping:

OneToOne(x => x.Passport, x => x.Cascade(Cascade.All));

PassportMapping:

ManyToOne(x => x.Person, x => { x.Unique(true); x.Column("PersonId");});

it is constructing the sql query as follows

select * from Person
left outer join  Passport on Persson.PersonId = Passport.PassportId.

it assumes that the PassportId and PersonId has same value but in my case they are different. How can I define my mapping in such case using mapping by code.

I hope that my post will help you, I will show you how I am doing these kind of mappings: Mapping for Person:

  HasOne(x=>x.Passport).Cascade.All();

and the Passport:

  References(x => x.Person).Unique();

hopes this helps. Later on, when you want to create a new record do this for example:

 var person = new Person();
 person.Passport = new Passport(){Person = person};

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