Nhibernate One-To-One mapping by code
Asked Answered
B

2

6

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.

Bonham answered 19/9, 2014 at 18:45 Comment(0)
D
1

I know this is a really old question, but I wasted way too much time trying to solve this so I'm adding my solution anyway.

Person mapping:

OneToOne(x => x.Passport, m =>
{
    m.Access(Accessor.Property);
    //if you are running an older version of NHibernate like 3.3.4 you might need to do it this way
    //m.PropertyReference(typeof(Passport).GetProperty("Person"));  
    m.PropertyReference(p => p.Person);
    m.Constrained(false);
});

Passport mapping:

ManyToOne(x => x.Person, m =>
{
    m.Column("PersonId")
    m.Unique(true);
    m.NotFound(NotFoundMode.Ignore);
});
Distinction answered 17/5, 2023 at 4:41 Comment(1)
Worked for me because database structure was wrong (same case) thank :)Postpone
A
-2

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};
Alford answered 19/9, 2014 at 23:56 Comment(1)
This ansver is using fluent nhibernate but the question is for Mapping By Code.Adai

© 2022 - 2024 — McMap. All rights reserved.