使用 ASP.NET 的 Identity2 与 EntityFramework 创建用户体系

本文写于2016年10月31日,因为只是在学习过程中的一些记录,当时觉得公开发布的话可能还不太完善,于是只放到了 blogspot 上,现在发现 Google 基本已经不管 blogspot 了,也不会支持 Markdown,于是还是搬到简书上来吧。


使用项目样例

创建空项目并安装样例

首先可以创建一个空项目,然后使用Nuget命令行
Install-Package Microsoft.AspNet.Identity.Samples -Pre
将项目转换为相关样例,官方网址为:
https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples

修改数据库连接

样例的数据库使用了自带的 LocalDB,如果有 SQL Server 的环境,可以在 Web.config 中创建一个相关连接,然后在 IdentityModels.cs 文件中将连接改为相应的连接名。

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext() : base("EntityModel", throwIfV1Schema: false)
    {
    }
    ...
}

上面使用官方样例在 VS2015 下会不成功,不知道是否与环境有关,如果这样的话,直接创建一个带个人验证的项目也是可以的,基本的用户体系功能也会有。

创建默认用户数据库与已存在数据一对一的关系

修改数据库属性

假设已经存在名字为 Staff 的数据库表,Identity 模块自动创建的用户表为 AspNetUsers,为了将两个表创建一对一的关系,需要对数据进行修改,为了避免系统创建的 AspNetUsers 表因为修改而产生未知的错误,决定修改 Staff 表。

而关于在 SQL Server 中创建表关系在 StackOverflow上有这么一个回答表述得很好:

Any relationship requires that the "parent" table (the one side) have a Primary (or unique) Key (PK), that uniquely identifies each row, and the "child" table (the other side) have a Foreign Key column or columns, that must be populated with values that are the same as some existing value[s] of the Primary Key in the parent table. If you want a one to many (1-M) relationship then the Foreign Key should be an ordinary attribute (column or columns) in the child table that can repeat (there can be many rows with the same value)

If you want a one to one (1-1) relationship then the Foreign key should itself be a Primary Key or unique index in the child table that guarantees that there may be at most one row in the child table with that value.

A 1-1 relationship effectively partitions the attributes (columns) in a table into two tables. This is called vertical segmentation. This is often done for sub-classing the table entities, or, for another reason, if the usage patterns on the columns in the table indicate that a few of the columns need to be accessed significantly more often than the rest of the columns. (Say one or two columns will be accessed 1000s of times per second and the other 40 columns will be accessed only once a month). Partitioning the table in this way in effect will optimize the storage pattern for those two different queries.

Sub-Classing. The above actually creates a 1 to zero or one relationship, which is used for what is called a sub-class or subtype relationship. This occurs when you have two different entities that share a great number of attributes, but one of the entities has additional attributes that the other does not need. A good example might be Employees, and SalariedEmployees. The Employee table would have all the attributes that all employees share, and the SalariedEmployee table would exist in a (1-0/1) relationship with Employees, with the additional attributes (Salary, AnnualVacation, etc.) that only Salaried employees need.

If you really want a 1-1 relationship, then you have to add another mechanism to guarantee that the child table will always have one record for each record/row in the parent table. Generally the only way to do this is by enforcing this in the code used to insert data (either in a trigger, stored procedure or code outside the database). This is because if you added referential integrity constraints on two tables that require that rows always be in both, it would not be possible to add a row to either one without violating one of the constraints, and you can't add a row to both tables at the same time.

参见 http://stackoverflow.com/questions/5112473/designing-11-and-1m-relationships-in-sql-server
另外还有一篇文章举了不错的例子 http://www.tech-recipes.com/rx/56738/one-to-one-one-to-many-table-relationships-in-sql-server/

上面说了,我们准备在 Staff 表中进行一定的修改,首先创建一个字段用于作为 AspNetUsers 的外键: aspNetUserId,注意类型需要与要关联的另一个表的字段,即 Id 要相同,然后将这个字段设置为唯一的索引属性,但是你会发现这个设置并不能成功,因为唯一的属性需要这个字段上的值是不同的,而观察这个字段属性,发现勾选了允许为 null,但是如果去掉的话,显然不能成功,因为这个字段是新加入的列,上面是不能有值的,当然,你可以用Excel生成一个等差序列先将这个空白填上。

填充关联数据

刚才填充数据的那个操作只完成了一小半的工作,由于我们的最终目的是要关联两个表,因此我们需要真实的数据来进行表的数据是最科学,也是必须的。

由于 Identity2 默认的程序里已经自带了创建用户的功能,因此我们改造下程序,使用 Staff 表中的登录账号生成 AspNetUsers 的相关账号信息,然后将 AspNetUsersId 值同时保存至 Staff 新建字段 aspNetUserId 中即可(这里程序就不说了,很简单,看看代码就应该知道如何操作了)。

建立两个表的一对一关系

数据已经填充好,现在重复之前说的,将 Staff 中的字段 aspNetUserId 设置为唯一索引属性,然后在 Staff 创建关系,相关联的字段当然是 aspNetUserIdAspNetUsersId 字段,保存后即可看到两个表上出现了一对一的连接关系。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,165评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,720评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,849评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,245评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,596评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,747评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,977评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,708评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,448评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,657评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,141评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,493评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,153评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,890评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,799评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,685评论 2 272

推荐阅读更多精彩内容