我如何确定在执行时如何生成 NHibernate 实体密钥?

How can I determine how an NHibernate entity key is generated at execution time?

我已将 Identity Entity Framework 项目改编为 NHibernate 版本。现在我有一个 ApplicationUser class 这样的:

public class ApplicationUser : IdentityUser<TKey>
{
    // TODO Auto determine if Id must be generated here or at DB.
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, TKey> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

        // Add custom user claims here
        return userIdentity;
    }
}

在我当前的项目中,我们对所有内容都使用 int 键,由数据库中的 Identity 字段支持。在这种情况下,我更喜欢生成一个负整数临时 id 的方法,而不是使用 manager.CreateIdentityAsync,但是如果我像通常使用的那样使用 Identity,而 typeof(TKey)string,我希望这个方法能正常工作。

但是,注意,我不关心 id 的类型,而是我是否必须在我的应用程序中生成它,或者数据库是否会为我生成它,这就是我想知道的在 运行 时间。

您需要使用 SessionFactory:

获取标识符生成器
var generator = ((ISessionFactoryImplementor)Session.SessionFactory)
    .GetIdentifierGenerator(typeof(TEntity).FullName);

if (generator is Assigned)
{
    // Generate the identifier
}