NHibernate:如何强制在父/子关系中生成子ID

NHibernate:如何强制在父/子关系中生成子ID,nhibernate,identity,one-to-many,Nhibernate,Identity,One To Many,我在用户和会话之间有一对多的父/子关系。以下是映射: <class name="ApplicationUser" table="APPLICATION_USER" lazy="true"> <id name="Id" column="APPLICATION_USER_ID"> <generator class="guid.comb" /> </id> <property name="UserName"

我在用户和会话之间有一对多的父/子关系。以下是映射:

<class name="ApplicationUser" table="APPLICATION_USER" lazy="true">
    <id name="Id" column="APPLICATION_USER_ID">
         <generator class="guid.comb" />
    </id>
    <property name="UserName" column="USER_NAME" />
    <property name="Password" column="PASSWORD" />
    <bag name="UserSessions" lazy="true" cascade="all-delete-orphan" inverse="true">
        <key column="APPLICATION_USER_ID"></key>
        <one-to-many class="UserSession"></one-to-many>
    </bag>
</class>

<class name="UserSession" table="USER_SESSION" lazy="true">
    <id name="Id" column="USER_SESSION_ID">
         <generator class="guid.comb" />
    </id>
    <property name="Created" column="CREATED" />
    <many-to-one name="ApplicationUser" column="APPLICATION_USER_ID" class="ApplicationUser" unique="true" />
</class>
当用户登录时,会发生多个数据库交互,并封装在一个事务中。除了创建新的用户会话之外,我还希望能够审核用户是否已登录,并将新会话ID与审核数据一起包括在内。但是,由于UserSession尚未持久化,因此其ID为空

我尝试保存ApplicationUser以生成用户会话ID:

IApplicationUserManager manager = ManagerFactory.GetApplicationUserManager();
ApplicationUser user = manager.GetById(userId);

user.LogInUser();
manager.Save(user);
我认为这会起作用,因为有了“全部删除孤立级联”设置,但事实并非如此。有没有办法在
Flush()
或事务提交之前强制生成ID

有没有办法在Flush()或事务提交之前强制生成ID

否。我将对UserSession类使用
,并在类的构造函数中初始化它

另外,在将密码作为属性公开时,您可能需要三思。

调用Session.Save(这是NHibernate的Session btw)应该生成ID。这是使用GUID的主要原因之一-可以在不访问数据库的情况下生成它们


如果保存未从ApplicationUser级联,则只需手动将UserSession传递到Session.save。我不明白为什么这会是个问题。

谢谢。密码是加密的,因此不像看上去那样公开。:-)这个问题实际上与我的架构有关。我使用的是数据访问对象(DAO),因此每个域模型类有一个DAO(根据需要)。会话保存实际上被抽象为DAO上的一个方法。在我的代码片段中,我通过调用manager.save(user)来保存应用程序管理器,但是这个保存方法是特定于类型的。我必须实例化一个UserSession DAO来单独保存它。这是可能的,但我希望有更优雅的。好的,我明白你的意思。如果是我的代码,我只需要创建usersessiondao并使用它来保存会话对象。我看不出这有什么问题,而且如果你开始改变映射或设计,似乎会让你自己陷入更多的麻烦。
IApplicationUserManager manager = ManagerFactory.GetApplicationUserManager();
ApplicationUser user = manager.GetById(userId);

user.LogInUser();
manager.Save(user);