c# - 我如何确定在执行时如何生成 NHibernate 实体 key ?

标签 c# nhibernate asp.net-identity

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

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 字段支持。在这种情况下,我更喜欢该方法生成一个负的 int 临时 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
}

关于c# - 我如何确定在执行时如何生成 NHibernate 实体 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34909410/

相关文章:

c# - 如何从驱动器全名获取驱动器号

nhibernate - 如何告诉 NHibernate 总是强制引用标识符?

c# - 如何检测用户何时使用 Microsoft.AspNet.Identity 登录

asp.net-core - 我应该使用 IEmailSender 吗?

c# - 实体类型 'Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>' 需要定义键

c# - 如何为 Dispatcher.BeginInvoke 提供回调函数

C# 使用 JSON 进行序列化

c# - 使用自己的 PowerShell CmdLets 将管理命令发送到我的 C# Windows 服务

nhibernate - 使用 Autofac 管理 NHibernate ISession

c# - NHibernate 按代码映射和 IUsertype 不工作