如何在nHibernate中映射关系?

时间:2022-04-21 11:28:25

Schema:

  • Users
    • ID
    • Name
    • Password
  • 用户ID名称密码

  • Address
    • ID
    • Street
    • UserID
  • 地址ID Street UserID

Both tables have an ID field (guid).

两个表都有一个ID字段(guid)。

Code:

User u = new User();
u.Address.Street = "test";
session.Save(u);

How can I create a mapping file to use the UserID from the address table to point to the ID from the Users table and reflect my sample code above?

如何创建映射文件以使用地址表中的UserID指向Users表中的ID并反映上面的示例代码?


Using many-to-one i sucessfully solve my problem.

使用多对一,我成功地解决了我的问题。

but i go search more samples!!

但我去搜索更多样品!!

thanks!!

1 个解决方案

#1


In most of the cases, such kind of mapping should lead to a 'component'.
In your case, Address could be a component of User. This means that you'll have indeed an Adress class, and the User class will have a property of type Adress, but the Address is saved in the Users table in the DB.

在大多数情况下,这种映射应该导致“组件”。在您的情况下,Address可以是User的一个组件。这意味着您确实会有一个Adress类,而User类将具有Adress类型的属性,但该地址将保存在DB的Users表中。

If you really want a one-to-one mapping with the DB layout like you want, I suggest you create a one-to-one mapping in the User mapping, and a many-to-one mapping in the Address mapping (with unique set to true). But, I think that this also means that you will be responsible of deleting the old address first if you update the adress of a user ...

如果你真的想要像你想要的那样与数据库布局进行一对一的映射,我建议你在用户映射中创建一对一映射,在地址映射中创建多对一映射(具有唯一性)设为真)。但是,我认为这也意味着如果您更新用​​户的地址,您将首先负责删除旧地址...

#1


In most of the cases, such kind of mapping should lead to a 'component'.
In your case, Address could be a component of User. This means that you'll have indeed an Adress class, and the User class will have a property of type Adress, but the Address is saved in the Users table in the DB.

在大多数情况下,这种映射应该导致“组件”。在您的情况下,Address可以是User的一个组件。这意味着您确实会有一个Adress类,而User类将具有Adress类型的属性,但该地址将保存在DB的Users表中。

If you really want a one-to-one mapping with the DB layout like you want, I suggest you create a one-to-one mapping in the User mapping, and a many-to-one mapping in the Address mapping (with unique set to true). But, I think that this also means that you will be responsible of deleting the old address first if you update the adress of a user ...

如果你真的想要像你想要的那样与数据库布局进行一对一的映射,我建议你在用户映射中创建一对一映射,在地址映射中创建多对一映射(具有唯一性)设为真)。但是,我认为这也意味着如果您更新用​​户的地址,您将首先负责删除旧地址...