How to Authenticate using MVC5RC/RTW with existing database

前端 未结 3 741
误落风尘
误落风尘 2021-01-19 02:36

I originally asked this question when Identity was in beta. The classes and interfaces have changed considerably since then and it appears the RTW version has some modificat

3条回答
  •  情歌与酒
    2021-01-19 03:08

    You can do this easily by modifying the IdentityModel.cs as per the below:

    Override OnModelCreating in your DbContext then add the following, this will change AspNetUser table to "Users" you can also change the field names the default Id column will become User_Id.

    modelBuilder.Entity()
                        .ToTable("Users", "dbo").Property(p => p.Id).HasColumnName("User_Id");
    

    or simply the below if you want to keep all the standard column names:

    modelBuilder.Entity()
                            .ToTable("Users", "dbo")
    

    Full example below (this should be in your IdentityModel.cs file) i changed my ApplicationUser class to be called User.

    public class User : IdentityUser
        {
            public string PasswordOld { get; set; }
            public DateTime DateCreated { get; set; }
    
            public bool Activated { get; set; }
    
            public bool UserRole { get; set; }
    
        }
    
    public class ApplicationDbContext : IdentityDbContext
        {
            public ApplicationDbContext()
                : base("DefaultConnection")
            {
            }
    
            protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
                modelBuilder.Entity()
                    .ToTable("Users", "dbo").Property(p => p.Id).HasColumnName("User_Id");
                modelBuilder.Entity()
                    .ToTable("Users", "dbo").Property(p => p.Id).HasColumnName("User_Id");
            }
        }
    

    Please note i have not managed to get this working if the current table exists. Also note whatever columns you do not map the default ones will be created.

    Hope that helps.

提交回复
热议问题