Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OneToOne mapping by code nhibernate 3.2

Tags:

nhibernate

I'm trying to upgrade a project and use the build in code mapper.

I have 2 entities:

public class Person {
 public virtual int Id { get; set; }
 public virtual User User { get; set; }
}

public class User {
 public virtual int Id { get; set; }
 public virtual User Person { get; set; }
}

The database structure is like this:

table: users, fields: id
table: people, fields: id, userId

With FluentNHibernate i could map it like this:

public class UserMap : ClassMap<User> {
 public UserMap() {
  Id(x => x.Id).GeneratedBy.Identity();
  HasOne(x => x.Person).PropertyRef("User").Not.LazyLoad();
 }
}

public class PersonMap : ClassMap<Person> {
 public PersonMap() {
  Id(x => x.Id).GeneratedBy.Identity();
  References(x => x.User).Column("UserId").Not.Nullable().Not.LazyLoad();
 }
}

But is can't get it working with NH 3.2 build in code mapper. This is what i have done so far.

OneToOne(x=>x.Person, m => {
 m.PropertyReference(typeof(Person).GetProperty("User"));
});

OneToOne(x=>x.User, m => {});

Now the relation is mapped on User.Id and Person.Id but personid and userid can be different. It's also possible that a user has no person.

from Users user0_ left outer join People person1_ on user0_.Id=person1_.Id 

I think i have to specify that Person -> User is mapped with the UserId column but how?.

like image 321
Bas Avatar asked Oct 30 '11 12:10

Bas


1 Answers

Since you were using References() in Fluent, you need to convert that to ManyToOne():

public class UserMap : ClassMapping<User>
{
    public UserMap()
    {
        Id(x => x.Id, x => x.Generator(Generators.Identity));
        OneToOne(x => x.Person,
                 x => x.PropertyReference(typeof(Person).GetProperty("User")));
    }
}

public class PersonMap : ClassMapping<Person>
{
    public PersonMap()
    {
        Id(x => x.Id, x => x.Generator(Generators.Identity));
        ManyToOne(x => x.User,
                  x => x => { x.Column("UserId"); x.NotNullable(true); });
    }
}

Two notes:

  • The type of User.Person should be Person, not user (that's probably just a bad edit)
  • .Not.LazyLoad() is almost always a bad idea. See NHibernate is lazy, just live with it
like image 191
Diego Mijelshon Avatar answered Oct 06 '22 00:10

Diego Mijelshon