使用 NHibernate.AspNet.Identity [英] Using NHibernate.AspNet.Identity

查看:16
本文介绍了使用 NHibernate.AspNet.Identity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Asp.net 身份和 NHibernate.

I am attempting to use Asp.net identity and NHibernate.

我使用 .NET framework 4.5.1 创建了一个新的空白 Asp.net MVC 站点,并且我已经安装并遵循了使用 nuget 包 NHibernate.AspNet.Identity 的说明,如下所述:

I have created a new blank Asp.net MVC site using .NET framework 4.5.1 and I have installed and followed the instructions for using nuget package NHibernate.AspNet.Identity as described here:

https://github.com/milesibastos/NHibernate.AspNet.Identity

这涉及对 AccountController 类的默认构造函数进行以下更改:

which involves making the following changes to the AccountController class default constructor:

var mapper = new ModelMapper();
mapper.AddMapping<IdentityUserMap>();
mapper.AddMapping<IdentityRoleMap>();
mapper.AddMapping<IdentityUserClaimMap>();
mapper.AddMapping<IdentityUserLoginMap>();

var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
var configuration = new Configuration();
configuration.Configure(System.Web.HttpContext.Current.Server.MapPath(@"~Modelshibernate.cfg.xml"));
configuration.AddDeserializedMapping(mapping, null);

var schema = new SchemaExport(configuration);
schema.Create(true, true);

var factory = configuration.BuildSessionFactory();
var session = factory.OpenSession();

UserManager = new UserManager<ApplicationUser>(
                new UserStore<ApplicationUser>(session));

我收到以下异常:

没有持久化程序:IdentityTest.Models.ApplicationUser

No persister for: IdentityTest.Models.ApplicationUser

ApplicationUser 类没有 IdentityUser 的任何其他属性(这适用​​于 Asp.net Identity 的实体框架实现).

The ApplicationUser class doesn't have any additional properties to IdentityUser (which works fine for a Entity Framework implementation of Asp.net Identity).

谁能就我如何获得 Asp.net 身份以使用此 NuGet 包提供建议?

Can anyone offer suggestions as to how I can get Asp.net identity to work with this NuGet package?

推荐答案

我在使用这个库时遇到了很多困难,这让我怀疑为什么这是将 OWIN 与 NHibernate 一起使用的推荐库.

I have struggled very much with this library, which is making me question why this is the recommended library for using OWIN with NHibernate.

无论如何,为了回答您的问题,您提供的从 github 网站获得的代码为库的类添加了 NHibernate 映射.NHibernate 没有 ApplicationUser 的映射,它只有它的基类的映射.NHibernate 需要一个实例化类的映射.这是有问题的,因为您无权访问库程序集中的映射代码,因此您无法将其更改为使用 ApplicationUser 类.因此,使用库解决此问题的唯一方法是删除 ApplicationUser 类并使用库的 IdentityUser 类.或者,您可以从 github 复制映射代码并尝试对 ApplicationUser 使用相同的映射.

Anyway, to answer your question, the code you provided that you got from the github website adds NHibernate mappings for the library's classes. NHibernate doesn't have a mapping for ApplicationUser, it only has a mapping for it's base class. NHibernate needs a mapping for the instantiated class. This is problematic because you don't have access to the mapping code in the library's assembly, so you can't change it to use the ApplicationUser class instead. So the only way to get past this using the library as it is, is to remove the ApplicationUser class and use the library's IdentityUser class. Or, you could copy the mapping code from github and try using the same mapping for ApplicationUser.

此外,库代码和他为 AccountController 提供的代码永远不会打开 NHibernate 事务,因此即使库调用了 Session.SaveSession.Update 数据最终不会保存在数据库中.打开会话后,您需要打开一个事务并将其保存为类上的私有字段:

Also, the library code and the code he gives for the AccountController does not ever open an NHibernate transaction, so even though the library calls Session.Save and Session.Update the data won't ultimately be saved in the database. After you open the session you need to open a transaction and save it as a private field on the class:

transaction = session.BeginTransaction(IsolationLevel.ReadCommitted);

然后您需要在 AccountController 中的操作完成执行后调用 transaction.Commit(),因此您需要覆盖 OnResultExecuted:

Then you need to call transaction.Commit() after your action in the AccountController finishes executing, so you will need to override OnResultExecuted:

protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
    transaction.Commit();
}

请记住,此示例过于简单,在生产应用程序中,您需要进行错误检查,如果出现错误,您将在何处回滚而不是提交,并且您需要正确关闭/处理所有内容等.

Keep in mind this example is oversimplified, and in a production application you need to have error checking where you will Rollback instead of Commit if there are errors, and you need to properly close/dispose of everything, etc.

此外,即使您解决了这些问题,该库还存在其他问题.我最终不得不从 github 下载源代码,以便我可以修改库以使用它.库代码中至少还有 3 个其他明显错误:

Furthermore, even after you solve those problems, there are other issues with the library. I ended up having to download the source from github so I could modify the library in order to use it. There are at least 3 other blatant errors in the library's code:

1) 在 NHibernate.AspNet.Identity.UserStore 中:

public virtual async Task<TUser> FindAsync(UserLoginInfo login)
{
    this.ThrowIfDisposed();
    if (login == null)
        throw new ArgumentNullException("login");

    IdentityUser entity = await Task.FromResult(Queryable
        .FirstOrDefault<IdentityUser>(
            (IQueryable<IdentityUser>)Queryable.Select<IdentityUserLogin, IdentityUser>(
                Queryable.Where<IdentityUserLogin>(
                    // This line attempts to query nhibernate for the built in asp.net
                    // UserLoginInfo class and then cast it to the NHibernate version IdentityUserLogin, 
                    // which always causes a runtime error. UserLoginInfo needs to be replaced 
                    // with IdentityUserLogin
                    (IQueryable<IdentityUserLogin>)this.Context.Query<UserLoginInfo>(), (Expression<Func<IdentityUserLogin, bool>>)(l => l.LoginProvider == login.LoginProvider && l.ProviderKey == login.ProviderKey)),
                    (Expression<Func<IdentityUserLogin, IdentityUser>>)(l => l.User))));

    return entity as TUser;
}

2) 在 NHibernate.AspNet.Identity.DomainModel.ValueObject 中:

protected override IEnumerable<PropertyInfo> GetTypeSpecificSignatureProperties()
{
    var invalidlyDecoratedProperties =
        this.GetType().GetProperties().Where(
            p => Attribute.IsDefined(p, typeof(DomainSignatureAttribute), true));

    string message = "Properties were found within " + this.GetType() +
                                        @" having the
            [DomainSignature] attribute. The domain signature of a value object includes all
            of the properties of the object by convention; consequently, adding [DomainSignature]
            to the properties of a value object's properties is misleading and should be removed. 
            Alternatively, you can inherit from Entity if that fits your needs better.";

    // This line is saying, 'If there are no invalidly decorated properties, 
    // throw an exception'..... which obviously should be the opposite, 
    // remove the negation (!)
    if (!invalidlyDecoratedProperties.Any())
        throw new InvalidOperationException(message);

    return this.GetType().GetProperties();
}

3) 在 NHibernate.AspNet.Identity.UserStore 中:出于某种原因,至少在使用 facebook 等外部提供程序创建用户/用户登录时,最初创建用户/用户登录时, Update 方法被调用而不是 Add/Create 导致 NHibernate 尝试更新一个不存在的实体.现在,没有深入研究,在 UserStore 更新方法中,我将库的代码更改为在 NHibernate 会话上调用 SaveOrUpdate 而不是 Update解决了问题.

3) In NHibernate.AspNet.Identity.UserStore: For some reason, at least when creating a user/user login using an external provider like facebook, when the user/user login is initially created, the Update method is called instead of the Add/Create causing NHibernate to try to update an entity that doesn't exist. For now, without looking more into it, in the UserStore update methods I changed the library's code to call SaveOrUpdate on the NHibernate session instead of Update which fixed the problem.

我只对在我更改后起作用的库运行了简单的测试,所以不知道这个库中有多少其他运行时/逻辑错误.发现这些错误后,现在使用它让我非常紧张.即使是简单的场景,似乎也绝对没有进行过测试.谨慎使用此库.

I have only ran simple tests with the library that have worked after my changes, so there is no telling how many other runtime / logic errors are in this library. After finding those errors, it makes me really nervous using it now. It seems there was absolutely no testing done with even simple scenarios. Take caution using this library.

这篇关于使用 NHibernate.AspNet.Identity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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