为什么在调用flush之前NHibernate需要知道基于自动ID的实体的ID? [英] Why does NHibernate need to know the ID of an auto ID based entity before flush is called?

查看:82
本文介绍了为什么在调用flush之前NHibernate需要知道基于自动ID的实体的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我唯一的ORM知识是L2S/EF,当以下代码在调用repo.Save之前将一行插入数据库时​​,我感到很惊讶.

With my only ORM knowledge being L2S/EF, I was surprised when the following code inserted a row into the database before I called repo.Save:

var repo = new UserRepository();
var user = new User { Name = "test" }

repo.Add(user);

//repo.Save();

回购看起来像这样:

public void Add(T entity)
{
    session.Save(entity);
}

public void Save()
{
    session.Flush();
}

进行一些挖掘之后,NHibernate似乎需要立即进行插入操作才能获取新实体的ID(因为它使用的是自动增量ID).但是L2S/EF不能像这样工作.我可以添加许多实体并将其保存在最后.

After some digging, it seems NHibernate needs to make the insert happen right away in order to get the ID of the new entity (since it's using an auto increment ID). But L2S/EF doesn't work like this; I can add many entities and save them all at the end.

问题是:有没有办法使用NHibernate达到相同的目的,同时仍然使用自动增量ID,并且出于兴趣,有人知道为什么它会这样工作吗?

Question is: is there a way to achieve the same thing with NHibernate, while still using auto increment IDs, and out of interest does anyone know why it works like this?

推荐答案

Fabio Maulo已经在博客上多次介绍了身份生成器的用法.答案是:使用hilo,guid.comb或类似的东西.

Fabio Maulo already blogged about the usage of identity generator a few times. The answer is: use hilo, guid.comb or something like this.

NHibernate需要身份,因为会话中的每个实体(它们称为持久实体")都需要标识.该标识通常还用于确定记录是否已存在于数据库中(未保存的值).

NHibernate needs the identity because every entity in the session (they are called "persistent entities") needs to be identified. The identity is also normally used to determine if the record already exists in the database (unsaved value).

session.Save实际上仅使瞬态实体持久化.数据库生成ID时,需要对其进行存储以获取ID.如果NH可以自己创建id(例如使用hilo),则可以在下次刷新会话时将其存储.

session.Save actually only makes a transient entity persistent. When the database is generating the id, it needs to be stored to get the id. If NH can create the id itself (eg using hilo), it could be stored next time when the session gets flushed.

这篇关于为什么在调用flush之前NHibernate需要知道基于自动ID的实体的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆