博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET Core Identity自定义数据库结构和完全使用Dapper而非EntityFramework Core
阅读量:4597 次
发布时间:2019-06-09

本文共 12546 字,大约阅读时间需要 41 分钟。

前言

原本本节内容是不存在的,出于有几个人问到了我:我想使用ASP.NET Core Identity,但是我又不想使用默认生成的数据库表,想自定义一套,我想要使用ASP.NE Core Identity又不想使用EntityFramework Core。真难伺候,哈哈,不过我认为这个问题提出的非常有价值,所以就私下花了点时间看下官网资料,最终经过尝试还是搞出来了,不知道是否满足问过我这个问题的几位童鞋,废话少说,我们直接进入主题吧。

ASP.NET Core Identity自定义数据库表结构

别着急哈,我是那种从头讲到尾的人,博文基本上面向大众,没什么基础的和有经验的都能看明白,也不要嫌弃我啰嗦,好,我说完了,开始,开始,又说了一大堆。大部分情况下对于默认情况下我们都是继承自默认的身份有关的类,如下:

///     ///     ///     public class CusomIdentityDbContext : IdentityDbContext
{ ///
/// /// ///
public CusomIdentityDbContext(DbContextOptions
options) : base(options) { } } ///
/// /// public class CustomIdentityUser : IdentityUser { } ///
/// /// public class CustomIdentityRole : IdentityRole { }

然后添加身份中间件,最后开始迁移,如下:

services.AddIdentity
() .AddEntityFrameworkStores
() .AddDefaultTokenProviders(); services.AddDbContextPool
(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));

以上是默认为我们生成的数据表,我们可以指定用户表主键、可以修改表名、列名等等,以及在此基础上扩展属性都是可以的,但是我们就是不想使用这一套,需要自定义一套表来管理用户身份信息,那么我们该如何做呢?其实呢,官网给了提示,

如下链接:,只是说的不是很明确,然后有些童鞋就不知所措了,就是那么几个Store,自定义实现就好了,来,我们走一个。我们首先自定义用户,比如如下:

///     ///     ///     public class User    {        ///         ///         ///         public string Id { get; set; }        ///         ///         ///         public string UserName { get; set; }        ///         ///         ///         public string Password { get; set; }        ///         ///         ///         public string Phone { get; set; }    }

我们再来定义上下文,如下:

///     ///     ///     public class CustomDbContext : DbContext    {        ///         ///         ///         ///         public CustomDbContext(DbContextOptions
options) : base(options) { } ///
/// /// public DbSet
Users { get; set; } }

接下来实现IUserStore以及UserPasswordStore接口,接口太多,就全部折叠了

///     ///     ///     public class CustomUserStore : IUserStore
, IUserPasswordStore
{ private readonly CustomDbContext context; ///
/// /// ///
public CustomUserStore(CustomDbContext context) { this.context = context; } ///
/// /// ///
///
///
public Task
CreateAsync(User user, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
DeleteAsync(User user, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ///
/// /// ///
protected virtual void Dispose(bool disposing) { if (disposing) { context?.Dispose(); } } ///
/// /// ///
///
///
public Task
FindByIdAsync(string userId, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
GetNormalizedUserNameAsync(User user, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
GetPasswordHashAsync(User user, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
GetUserIdAsync(User user, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
GetUserNameAsync(User user, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
HasPasswordAsync(User user, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
///
public Task SetNormalizedUserNameAsync(User user, string normalizedName, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
///
public Task SetPasswordHashAsync(User user, string passwordHash, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
///
public Task SetUserNameAsync(User user, string userName, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
UpdateAsync(User user, CancellationToken cancellationToken) { throw new NotImplementedException(); } }
View Code

我们还要用到用户角色表,自定义用户角色

///     ///     ///     public class CustomUserRole    {        ///         ///         ///         public string Id { get; set; }        ///         ///         ///         public string UserId { get; set; }        ///         ///         ///         public string RoleId { get; set; }    }

接下来再来实现用户角色Store,如下:

///     ///     ///     public class CustomUserRoleStore : IRoleStore
{ ///
/// /// ///
///
///
public Task
CreateAsync(CustomUserRole role, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
DeleteAsync(CustomUserRole role, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// public void Dispose() { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
FindByIdAsync(string roleId, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
FindByNameAsync(string normalizedRoleName, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
GetNormalizedRoleNameAsync(CustomUserRole role, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
GetRoleIdAsync(CustomUserRole role, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
GetRoleNameAsync(CustomUserRole role, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
///
public Task SetNormalizedRoleNameAsync(CustomUserRole role, string normalizedName, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
///
public Task SetRoleNameAsync(CustomUserRole role, string roleName, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
UpdateAsync(CustomUserRole role, CancellationToken cancellationToken) { throw new NotImplementedException(); } }

简单来说就是根据需要,看看要不要实现如下几个Store罢了

  • IUserRoleStore
  • IUserClaimStore
  • IUserPasswordStore
  • IUserSecurityStampStore
  • IUserEmailStore
  • IPhoneNumberStore
  • IQueryableUserStore
  • IUserLoginStore
  • IUserTwoFactorStore
  • IUserLockoutStore

然后对于根据选择自定义实现的Store都进行注册,然后进行迁移,如下:

services.AddIdentity
() .AddDefaultTokenProviders(); services.AddDbContextPool
(options => options.UseSqlServer(Configuration.GetConnectionString("Default"))); services.AddTransient
, CustomUserStore>();

 

没什么难题,还是那句话,自定义实现一套,不过是实现内置的Store,其他通过定义的上下文正常去管理用户即可。然后什么登陆、注册之类只需要将对应比如UserManager泛型参数替换成对应比如如上CustomUser即可,这个就不用多讲了。接下来我们再来看第二个问题,如何不使用EntityFramework而是完全使用Dapper。

完全使用Dapper而不使用EntityFramework Core

其实讲解完上述第一个问题,这个就迎刃而解了,我们已经完全实现了自定义一套表,第一个问题操作表是通过上下文,我们只需将上下文更换为Dapper即可,如上我们定义了用户角色表,那我们通过Dapper实现角色表,如下定义角色:

///     ///     ///     public class CustomRole    {        ///         ///         ///         public string Id { get; set; }        ///         ///         ///         public string Name { get; set; }    }
///     ///     ///     public class CustomRoleStore : IRoleStore
{ private readonly IConfiguration configuration; private readonly string connectionString; ///
/// /// ///
public CustomRoleStore(IConfiguration configuration) { this.configuration = configuration; connectionString = configuration.GetConnectionString("Default"); } ///
/// /// ///
///
///
public async Task
CreateAsync(CustomRole role, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using (var connection = new SqlConnection(connectionString)) { await connection.OpenAsync(cancellationToken); role.Id = await connection.QuerySingleAsync
($@"INSERT INTO [CustomRole] ([Id],[Name]) VALUES (@{Guid.NewGuid().ToString()} @{nameof(CustomRole.Name)}); SELECT CAST(SCOPE_IDENTITY() as varchar(36))", role); } return IdentityResult.Success; } ///
/// /// ///
///
///
public Task
DeleteAsync(CustomRole role, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// public void Dispose() { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
FindByIdAsync(string roleId, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
FindByNameAsync(string normalizedRoleName, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
GetNormalizedRoleNameAsync(CustomRole role, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
GetRoleIdAsync(CustomRole role, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
GetRoleNameAsync(CustomRole role, CancellationToken cancellationToken) { return Task.FromResult(role.Name); } ///
/// /// ///
///
///
///
public Task SetNormalizedRoleNameAsync(CustomRole role, string normalizedName, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
///
public Task SetRoleNameAsync(CustomRole role, string roleName, CancellationToken cancellationToken) { throw new NotImplementedException(); } ///
/// /// ///
///
///
public Task
UpdateAsync(CustomRole role, CancellationToken cancellationToken) { throw new NotImplementedException(); } }

别忘记每自定义实现一个Store,然后进行对应注册

services.AddTransient
, CustomRoleStore>();

总结

这里已经提供了完全自定义实现一套表和不使用EntityFramework Core完全使用Dapper的思路,重申一句官网给出了几个Store,只是未明确说明而已,稍微思考并动手验证,其实问题不大。

转载于:https://www.cnblogs.com/CreateMyself/p/11291623.html

你可能感兴趣的文章
[iOS]数据库第三方框架FMDB详细讲解
查看>>
让IE6/IE7/IE8浏览器支持CSS3属性
查看>>
Windows 某些软件显示"口口"解决办法
查看>>
PHP+Hadoop+Hive+Thrift+Mysql实现数据统计分析
查看>>
和同事下班路上讨论心得(服务器部署的几点问题)
查看>>
Spring学习总结五——SpringIOC容器五
查看>>
解决多个ajax页面请求,页面loading阻塞问题
查看>>
Executor
查看>>
Javascript 表单验证对象控件 + ajax简单验证重复项与ajax提交数据
查看>>
使用抽象工厂设计一个简单的交易模块
查看>>
如何将广告始终定位到网页右下角
查看>>
常用js整理
查看>>
查看oracle/mysql数据库版本号
查看>>
memset函数
查看>>
使用postman+newman+python做接口自动化测试
查看>>
实体框架继承关系。很好
查看>>
201671010110 2016 2017 2《java程序设计》
查看>>
flask的基础认识
查看>>
静态blog的免费托管部署、加域名与搜索优化(SEO)
查看>>
oracle trunc(d1[,c1])
查看>>