gpt4 book ai didi

c# - 相关实体的NHibernate保存

转载 作者:太空宇宙 更新时间:2023-11-03 16:22:22 24 4
gpt4 key购买 nike

我有一个基本结构。一个 User 对象和一个 UserDetails 对象。 User表有标识主键生成UserId,然后我想也为这个UserId保存一个UserDetails对象。单独执行此操作很容易,但我试图找到一种方法,如果我可以一次性完成,因为 User 类包含对 UserDetails 对象的引用。例如

用户 u = new User() { Name="me", Age=17, UserDetails = new UserDetails() { Detail1 = 1 } };

所以我所要做的就是传递用户对象,然后它包含对其他相关子信息的基于对象的引用(对于这个例子我已经大大简化了它但是还有几个与 UserDetails 类似的类,比如 UserMatchConfiguration 等每个都有很多字段)

我希望能够在代码中构建对象,或者让它传递和修改,然后调用父 User 对象的保存,然后保存所有相关对象。到目前为止,我已经使用一对一映射和保存级联实现了这一点,但问题是当您创建一个新对象时,当我希望它首先保存 User 类时,所有相关类的 UserId 设置为零,然后将生成的 UserId 传播到所有相关类,然后保存它们。

目前映射如下。

<class name="User" table="[User]">
<id name="UserId" unsaved-value="0">
<generator class="identity" />
</id>
<property name="FirstName" />
<property name="LastName" />
<property name="EmailAddress" />
<property name="DateOfBirth" />
<property name="Gender" />
<property name="PostcodePartOne" />
<property name="PostcodePartTwo" />
<many-to-one name="UserLocation" column="UserLocationId" />
<property name="DateJoined" />
<property name="LastLoggedOn" />
<property name="Status"/>
<property name="StatusNotes" />
<bag name="Photos" order-by="DisplayOrder asc" inverse="true" lazy="false" cascade="all">
<key column="UserId" />
<one-to-many class="UserPhoto" />
</bag>
<bag name="Interests" inverse="true" lazy="false" cascade="all">
<key column="UserId" />
<one-to-many class="UserMatchInterest" />
</bag>
<bag name="Preferences" inverse="true" lazy="false" cascade="all">
<key column="UserId" />
<one-to-many class="UserPreference" />
</bag>
<one-to-one name="Profile" class="UserProfile" cascade="save-update" />
<one-to-one name="MatchCriteria" class="UserMatchCriteria" />
<one-to-one name="MatchLifestyle" class="UserMatchLifestyle" />
<property name="LastUpdated" />
</class>

如您所见,我现在仅使用 Profile 对象对其进行试用,以尝试使其正常工作。我怎样才能让主要的 User 对象先保存,然后将 UserId 传递给其他类,因为它们都使用它作为主键?

同样,我无法执行级联保存,然后在每个子类上手动设置 UserId 并分别保存它们,但我试图在一次调用中完成。

最佳答案

我会说你快到了。您的 user 类映射似乎是正确的,所以我怀疑是 UserProfile

NHibernate 完全支持这种关系类型,它是一对一 映射(如您所试)。虽然我们看不到 UserProfile 映射,但让我们按照文档对其进行扩展:

用户资料 hbm

<class name="UserProfile" table="[UserProfile]">
<id name="UserProfileId" column="UserId">
<generator class="foreign">
<param name="property">User</param>
</generator>
</id>
...
<one-to-one name="User" class="User" constrained="true"/>
</class>

UserProfile 需要这些属性:

public class UserProfile 
{
public virtual int UserProfileId { get; set; }
public virtual User User { get; set; }
...
}

在插入之前我们必须连接两端(这是非常重要的一步):

user.Profile =  profile;
profile.User = user;

如果 user.hbm.xml 中的级联映射如下所示:

 <one-to-one name="Profile" class="UserProfile" cascade="all" />

我们可以只保存一个用户,所有其他实体将(以正确的顺序)由 NHiberante 保留。无论如何都不需要处理 ID。

关于c# - 相关实体的NHibernate保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13517468/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com