Nhibernate One-To-One mapping by code

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

For example consider

Person Table 
   PersonId (pk)
   Name

      

and

Passport Table 
   PassportId (pk)
   Country
   PersonId

      

The two tables have one relationship to 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 the explain form in 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 builds sql query like this

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

      

it assumes PassportId and PersonId have the same value, but in my case they are different. How can I determine my collation in such a case using code-behind mapping.

+3


source to share


1 answer


I hope my post will help you, I will show you how I make visions like this: Mapping to Human:

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

      

and passport:



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

      

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

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

      

+2


source







All Articles