通过代码nhibernate 3.2的OneToOne映射

时间:2011-10-30 12:08:23

标签: nhibernate

我正在尝试升级项目并使用构建代码映射器。

我有两个实体:

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; }
}

数据库结构如下:

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

使用FluentNHibernate我可以像这样映射:

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();
 }
}

但是无法让它在代码映射器中使用NH 3.2构建。 这是我到目前为止所做的。

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

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

现在关系映射到User.Id和Person.Id,但personid和userid可以不同。 用户也可能没有人。

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

我想我必须指定那个人 - &gt;用户使用UserId列进行映射但是如何?。

1 个答案:

答案 0 :(得分:5)

由于您在Fluent中使用References(),因此需要将其转换为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); });
    }
}

两个注释:

  • User.Person的类型应该是Person,而不是用户(这可能只是一个糟糕的编辑)
  • .Not.LazyLoad()几乎总是一个坏主意。请参阅NHibernate is lazy, just live with it