简体   繁体   English

使用 Asp.Net 身份数据库第一种方法

[英]Using Asp.Net Identity DataBase first approach

I need to integrate Asp.Net latest MVC version with an existing database which has an additional column String Address to table dbo.AspNetUsers我需要将 Asp.Net 最新的 MVC 版本与现有数据库集成,该数据库具有表dbo.AspNetUsers的附加列String Address

I need to create an instance ApplicationUser which has property Address.我需要创建一个具有属性地址的实例ApplicationUser

Any idea how to do it?知道怎么做吗?

A possible solution which works for me, basically I am able to integrate Asp.Net Identity User Profiles with an existing Database. 一个可能对我有用的解决方案,基本上,我能够将Asp.Net Identity用户配置文件与现有数据库集成在一起。

Getting the Asp.Identity Tables: 获取Asp.Identity表:

  • Create an MVC Project with Authentication Individual User Account 使用身份验证个人用户帐户创建MVC项目
  • Open the DB listed under the DefaultConnection in Web.config. 打开Web.config中DefaultConnection下列出的数据库。 It will be called (aspnet-[timestamp] or something like that.) 它将被称为(aspnet- [timestamp]或类似名称。)
  • Script the database tables using SQL Server Management Studio (attach database for mdc). 使用SQL Server Management Studio(为mdc附加数据库)编写数据库表脚本。

Alternatively use something like http://identity.codeplex.com/ 或者使用类似http://identity.codeplex.com/的名称

Integrating with your existing db: 与您现有的数据库集成:

  • Insert the scripted tables into existing database in SQL Server Management Studio. 将脚本化的表插入SQL Server Management Studio中的现有数据库。
  • Customize and add relationships to ApplicationUser (if necessary). 自定义关系并将其添加到ApplicationUser(如果需要)。
  • Create new Web Project > MVC > DB First Project > Import DB with EF ... . 创建新的Web项目> MVC>数据库第一个项目>使用EF ...导入数据库。
  • In IdentityModels.cs change the ApplicationDbContext :base("DefaltConnection") to use your project's DbContext. 在IdentityModels.cs中,将ApplicationDbContext:base(“ DefaltConnection”)更改为使用项目的DbContext。

Now you have the Asp.Identity Tables in your db with ER model in your application. 现在,您的数据库中具有带有ER模型的数据库中的Asp.Identity表。

Asp.Identity Profile Adding new properties: Asp.Identity配置文件添加新属性:

  • Enable Entity Framework Code First Database Migrations, just in VS go under Tools 'Package Manager Console', 启用Entity Framework代码优先数据库迁移,只需在VS中转到“程序包管理器控制台”下的工具,
  • Execute the command “Enable-Migrations”; 执行命令“ Enable-Migrations”; Once we enabled the database migrations, we can go ahead and add new properties for our UserProfile 启用数据库迁移后,就可以继续为UserProfile添加新属性

  • To Add new properties modify IdentityModels.cs file, example: 要添加新属性,请修改IdentityModels.cs文件,例如:


public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailID { get; set; }
}

Add New Migration 添加新的迁移

  • Once we added the properties, bring the Package Manager Console and execute the following command. 添加属性后,打开Package Manager控制台并执行以下命令。

    Add-Migration “YouMigrationName” 添加迁移“ YouMigrationName”

This command will generate a database script file, now execute following command to run this script file against the database. 此命令将生成一个数据库脚本文件,现在执行以下命令以针对数据库运行此脚本文件。

Update-Database

Now, all the new properties will turn into table fields in the same database table. 现在,所有新属性都将变成同一数据库表中的表字段。

I hope it can help others, if you have a better idea please let me know. 我希望它可以帮助其他人,如果您有更好的主意,请告诉我。

I have been successful in integrating an existing database via Database First with Identity Framework 2.0. 我已经成功通过Database First与Identity Framework 2.0集成了现有数据库。 I have written a blog post on it here which uses ASP.NET MVC 5, Identity Framework 2.0, and the SPA template from Visual Studio 2013 Update 2 RTM. 我在这里写了一篇博客文章,其中使用ASP.NET MVC 5,Identity Framework 2.0和Visual Studio 2013 Update 2 RTM中的SPA模板。

I hope this helps anyone in their journey because it contains a few points not listed in one place which I had to figure out on my own. 我希望这对任何人都可以帮助,因为它包含了一些我未必自己找出的要点。

Take a look at these projects on GitHub: 看一下GitHub上的这些项目:

Which includes: 包括:

  • SQL Database Project Template for ASP.NET Identity 2.0 用于ASP.NET Identity 2.0的SQL数据库项目模板
  • Entity Framework Database-First Provider(s) 实体框架数据库优先提供者
  • Source Code and Samples 源代码和示例

在此处输入图片说明

I had recently the same problem.我最近遇到了同样的问题。 I had an apllication created with DBFirst aproach and I needed to add Identity.我有一个使用 DBFirst 方法创建的应用程序,我需要添加身份。 This is what I did.这就是我所做的。

  1. Install the next packages:安装下一个包:
 1. Microsoft.EntityFrameworkCore 2. Microsoft.EntityFrameworkCore.Design 3. Microsoft.EntityFrameworkCore.SqlServer 4. Microsoft.AspNetCore.Identity 5. Microsoft.AspNetCore.Identity.EntityFrameworkCore 6. Microsoft.AspNetCore.Aututhentication.JwtBearer
  1. Do DbContext inherit from IdentityDbContext, like this: DbContext 是否继承自 IdentityDbContext,如下所示:
public partial class BookStoresDBContext : IdentityDbContext
  1. OnModelCreating I called the base constructor in order to avoid an error like "'IdentityUserLogin' requires a primary key to be defined" OnModelCreating 我调用了基本构造函数以避免出现“'IdentityUserLogin' 需要定义主键”之类的错误
 protected override void OnModelCreating(ModelBuilder modelBuilder) {
     base.OnModelCreating(modelBuilder);
 }
  1. As far as it was a created project the StringConnection was already there, if not add it.至于它是一个创建的项目,StringConnection 已经存在,如果不添加的话。

  2. On the Startup.cs configure Identity service on ConfigureServices在 Startup.cs 上配置 ConfigureServices 上的身份服务


public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BookStoresDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("BookStoreDB")));

    services.AddIdentity<IdentityUser, IdentityRole>(options =>
    {
        options.Password.RequireDigit = true;
        options.Password.RequiredLength = 5;
    
    }).AddEntityFrameworkStores<BookStoresDBContext>()
    .AddDefaultTokenProviders();

}

  1. You can configure the Authetication service too您也可以配置身份验证服务

    services.AddAuthentication(auth => { auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, RequireExpirationTime = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Your key to encrypt")) }; });
  2. Then run the migration from the Package Manager Console然后从 Package 管理器控制台运行迁移

Add-Migration InitDb
  1. On the migration file, remove all the migrationBuilder.CreateTable for the tables you already have in your Database在迁移文件中,删除数据库中已有表的所有 migrationBuilder.CreateTable

  2. Update the Database from the Package Manager Console从 Package 管理器控制台更新数据库

Update-Database
  1. Then you will see the Identity Tables on your db然后你会在你的数据库上看到身份表

在此处输入图像描述

I hope it result usefull我希望它有用

Don't forget to add migrations and update the database.不要忘记添加迁移和更新数据库。 Otherwise it throws a dependecy injection exceptions for the identity.否则它会为身份抛出依赖注入异常。

public class MyUser : IdentityUser { public virtual MyUserInfo MyUserInfo { get; 公共类MyUser:IdentityUser {公共虚拟MyUserInfo MyUserInfo {get; set; 组; } } }}

public class MyUserInfo{ 
    public int Id { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 
public class MyDbContext : IdentityDbContext<MyUserInfo> //Edited to MyUserInfo
{ 
    public MyDbContext() 
        : base("DefaultConnection") 
    { 
    } 
    public System.Data.Entity.DbSet<MyUserInfo> MyUserInfo { get; set; } 
 } 

Getting Profile information 获取资料信息

When the User Logs in, you can display the profile information by doing the following Get the current logged in UserId , so you can look the user up in ASP.NET Identity system 当用户登录时,可以通过执行以下操作来显示配置文件信息:获取当前登录的UserId ,以便可以在ASP.NET Identity系统中查找用户

var currentUserId = User.Identity.GetUserId(); 

Instantiate the UserManager in ASP.Identity system so you can look up the user in the system 在ASP.Identity系统中实例化UserManager ,以便您可以在系统中查找用户

var manager = new UserManager<MyUser>(new UserStore<MyUser>(new MyDbContext())); 

Get the User object 获取用户对象

var currentUser = manager.FindById(User.Identity.GetUserId()); 

Get the profile information about the user 获取有关用户的个人资料信息

currentUser.MyUserInfo.FirstName 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将Asp.net身份与数据库一起使用 - how to Use Asp.net Identity with DataBase first approach 如何在ASP.NET MVC Core中使用数据库优先方法在现有数据库中实现Asp.net身份 - How to implement Asp.net identity with existing database using database first approach in asp.net mvc core 具有自己的表定义的ASP.NET身份实体框架数据库第一种方法 - Asp.net identity entity framework database first approach with own table defintion 如何使用ASP Net Identity 2.0,MySQL和数据库优先方法注册用户? - How to register a user using asp net identity 2.0, mysql and database first approach? 如何使用数据库优先方法读取 asp.net 内核中的表 - How to read tables in asp.net core, with database first approach Asp.net IDentity 2数据库优先AspNetUserLogins&#39;没有定义密钥 - Asp.net IDentity 2 Database First AspNetUserLogins' has no key defined 首先将属性添加到Asp.Net 2.0身份数据库 - Add Properties to Asp.Net 2.0 Identity Database first 在ASP.NET标识中添加与ApplicationUser类的关系(数据库优先) - Add relationships to the ApplicationUser class in ASP.NET Identity (Database First) 如何首先使用代码在已创建的数据库中创建ASP.net身份表? - How to create ASP.net identity tables in an already created database using code first? 如何使用ASP.NET Identity 2创建第一个root用户? - How to create the first root user using ASP.NET Identity 2?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM