62

I need to integrate Asp.Net latest MVC version with an existing database which has an additional column String Address to table dbo.AspNetUsers

I need to create an instance ApplicationUser which has property Address.

Any idea how to do it?

Vaibhav
  • 1,156
  • 2
  • 12
  • 27
GibboK
  • 71,848
  • 143
  • 435
  • 658

5 Answers5

59

A possible solution which works for me, basically I am able to integrate Asp.Net Identity User Profiles with an existing Database.

Getting the Asp.Identity Tables:

  • Create an MVC Project with Authentication Individual User Account
  • Open the DB listed under the DefaultConnection in Web.config. It will be called (aspnet-[timestamp] or something like that.)
  • Script the database tables using SQL Server Management Studio (attach database for mdc).

Alternatively use something like http://identity.codeplex.com/

Integrating with your existing db:

  • Insert the scripted tables into existing database in SQL Server Management Studio.
  • Customize and add relationships to ApplicationUser (if necessary).
  • Create new Web Project > MVC > DB First Project > Import DB with EF ... .
  • In IdentityModels.cs change the ApplicationDbContext :base("DefaltConnection") to use your project's DbContext.

Now you have the Asp.Identity Tables in your db with ER model in your application.

Asp.Identity Profile Adding new properties:

  • Enable Entity Framework Code First Database Migrations, just in VS go under Tools ‘Package Manager Console’,
  • Execute the command “Enable-Migrations”; Once we enabled the database migrations, we can go ahead and add new properties for our UserProfile

  • To Add new properties modify IdentityModels.cs file, example:


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.

    Add-Migration “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.

GibboK
  • 71,848
  • 143
  • 435
  • 658
  • 1
    Actually this doesn't work for me. I have enabled migrations, added new properties, added new migration but when I try to "Update-Database" it says "There is already an object named 'AspNetRoles' in the database.". So it seems, it doesn't update database, instead try to re-create it. – bsaglamtimur Jun 20 '14 at 13:19
  • 1
    May I know why all asp.net mvc use localdb as default authentication database? – Timeless Apr 23 '15 at 04:44
  • 29
    Why use migrations if it's database-first approach? My understanding is that migrations are used in code-first approach to apply code changes to the database – Andrey Dec 22 '15 at 02:55
  • Where does one actually locate "(aspnet-[timestamp] or something like that.)"? Does that live in the project folder? – Jamie M. Aug 05 '16 at 17:41
  • 13
    How come every database-first discussion I find regarding the entity tables involves code first? – Jonathan Wood Feb 03 '17 at 18:24
  • This works but It doen't match the requirements in the title "DataBase first approach" – Pastor Cortes Sep 22 '17 at 15:27
  • This is a solution for adding Asp.Net Identity tables to an existing database, without having to recreate the database. Other than that, it is still a code-first solution. – ataravati Apr 17 '18 at 20:14
20

Take a look at these projects on GitHub:

Which includes:

  • SQL Database Project Template for ASP.NET Identity 2.0
  • Entity Framework Database-First Provider(s)
  • Source Code and Samples

enter image description here

Konstantin Tarkus
  • 37,618
  • 14
  • 135
  • 121
  • Any one got any other resources as how to use https://github.com/kriasoft/AspNet.Identity as its documentation doesn't say much, What if I am not starting from scratch. I simply want to link my identity context to my db first context/. – Zapnologica Apr 07 '15 at 11:21
  • 1
    @Zapnologica, well.. it's more suited for database-first approach, where you generate EF DbContext / Model based on the actual db schema. – Konstantin Tarkus Apr 08 '15 at 11:40
  • So can it not be used with db first? Only way i can think is to re implement all the stores and use my own `dbContext` pointing to my db first model? – Zapnologica Apr 08 '15 at 12:20
  • @Zapnologica [ASP.NET Server Template](https://github.com/kriasoft/AspNet-Server-Template) project contains a complete sample of an ASP.NET Identity solution and EF DbFirst development appraoch. – Konstantin Tarkus Apr 09 '15 at 15:54
2

I had recently the same problem. I had an apllication created with DBFirst aproach and I needed to add Identity. 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:
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"
 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.

  2. On the Startup.cs configure Identity service on 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

Add-Migration InitDb
  1. On the migration file, remove all the migrationBuilder.CreateTable for the tables you already have in your Database

  2. Update the Database from the Package Manager Console

Update-Database
  1. Then you will see the Identity Tables on your db

enter image description here

I hope it result usefull

  • Advice for those like me who need **remedial** help: Do NOT `Scaffold-DbContext` / `dotnet ef dbcontext scaffold` against your existing 'AspNetxxx' tables. That model you would be generating already comes with Identity. Try this exercise: Build a code-first .NET 6 MVC app from the template with individual accounts. Do initial migration to create the DB. Run, register, log in/out. Then delete the migration folder in the solution and the migrations table in DB. The app still works fine. (Is it still code-first?) Look at `ApplicationDBContext.cs`. Now begin to think about your customizations. – Ian W Nov 23 '21 at 17:05
0

Don't forget to add migrations and update the database. Otherwise it throws a dependecy injection exceptions for the identity.

ouflak
  • 2,458
  • 10
  • 44
  • 49
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 05 '22 at 20:32
-2

public class MyUser : IdentityUser { public virtual 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

var currentUserId = User.Identity.GetUserId(); 

Instantiate the UserManager in ASP.Identity system so you can look up the user in the system

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 
everest
  • 103
  • 9