本文介绍了尝试在ASP.NET Identity 2.0中更改表名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改ASP.NET Identity 2.0使用的表的名称。我看到过各种类似的问题,但没有什么可以解决我的问题。例如这种解决方案:

似乎依赖于Code First(?)。无论如何,实现OnModelCreating对我没有任何作用。我已经将AspNetUsers和类似的表重命名为我自己的名字,希望能够使用这些表。我有一个现有的EF上下文(MyContext),我想使用,所以我修改它从IdentityDbContext派生(编辑t4模板),然后在Startup.Auth我有:

  UserManagerFactory =()=> 
{
var context = new MyContext();

Database.SetInitializer< MyContext>(new IdentityDbInitializer());

var userStore = new UserStore< IdentityUser>(context){
DisposeContext = true
};

返回新的UserManager< IdentityUser>(userStore);
};

但是,当我尝试登录时,会出现无法联系服务器的问题。我想象是因为我的UserStore无法知道在我的上下文中哪个用户表。我希望这是OnModelCreating代码可以做的,但我对此朦胧。我想象,UserStore仍在寻找一个AspNetUsers表,虽然我不知道这些名字来自哪里。我也对我的上下文修改t4模板感到不安 - 这是我应该从IdentityDbContext派生的方式吗?



非常感谢任何帮助。 >

解决方案

几个步骤:




  • 安装NuGet软件包: Microsoft.AspNet.Identity.EntityFramework

  • 添加连接字符串到您的web.config / app.config



现在您必须定义自定义数据库上下文

  public class MyContext:IdentityDbContext 
{
public MyContext()
:base(< connection string name>)
{

}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.Entity< IdentityUser>()
.ToTable(Users);

modelBuilder.Entity< IdentityRole>()
.ToTable(Roles);

modelBuilder.Entity< IdentityUserRole>()
.ToTable(UserRoles);

modelBuilder.Entity< IdentityUserClaim>()
.ToTable(UserClaims);

modelBuilder.Entity< IdentityUserLogin>()
.ToTable(UserLogins);
}
}

正如你所看到的,我使用了 DbModelBuilder 将所有实体映射到新表。




  • 打开NuGet软件包管理器控制台

  • 执行命令启用迁移



它将创建一个文件夹 Migrations 配置文件 Configuration.cs



应该看起来像这样:

 内部密封类配置:DbMigrationsConfiguration< ConsoleApplication1.Models.MyContext> 
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}

protected override void Seed(ConsoleApplication1.Models.MyContext context)
{

}
}

在构造函数中将属性 AutomaticMigrationsEnabled 更改为


  • 打开NuGet软件包管理器控制台

  • 执行命令更新数据库



它应该运行脚本来创建新表。 / p>

您可以自定义您的实体(和Ids)为定义的每个界面创建自定义类。

 code> public class MyUser:IdentityUser< string,MyUserLogin,MyUserRole,MyUserClaim> 
{
}

由于您使用Owin,您可以定义您的UserStore :

  public class MyUserStore:UserStore&MyEservice,MyRole,string,MyUserLogin,MyUserRole,MyUserClaim> 
{
public MyUserStore(MyContext context)
:base(context)
{
}
}

和您的UserManager实现:

  public class ApplicationUserManager :UserManager< ASPNETIdentity2.Models.MyUser,string> 
{
public ApplicationUserManager(IUserStore< ASPNETIdentity2.Models.MyUser,string> store)
:base(store)
{

}

public static ApplicationUserManager创建(IdentityFactoryOptions< ApplicationUserManager>选项,IOwinContext上下文)
{
var manager = new ApplicationUserManager(new MyUserStore(context.Get< MyContext>()));

manager.UserValidator = new UserValidator< MyUser,string>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};

manager.PasswordValidator = new PasswordValidator()
{
RequiredLength = 5,
RequireNonLetterOrDigit = false,// true
// RequireDigit = true,
RequireLowercase = false,
RequireUppercase = false,
};

return(manager);
}
}

您的 Owin.Startup 应该如下所示:

  public class Startup 
{
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext(MyContext.Create);
app.CreatePerOwinContext< ApplicationUserManager>(ApplicationUserManager.Create);
}
}

如果您想查看自定义实现您可以使用ASP.NET上的简单工作解决方案查看我的 MVC。



更新:



该解决方案中还有一个最小设置的项目;基本上你只需要定义你的上下文( IdentityDbContext ),如果你只想重命名你的表。



该项目可以找到。


I want to change the names of the tables used by ASP.NET Identity 2.0. I've seen various similar questions but nothing that solves my problem. For instance this type of solution:http://www.goatly.net/customizing-table-names-for-identitydbcontextwithcustomuser-data-contextsseems to depend on Code First(?). At any rate implementing OnModelCreating does nothing for me. I've basically renamed the AspNetUsers and similar tables to my own names and want to be able to use these. I have an existing EF context (MyContext) that I want to use, so I modified it to derive from IdentityDbContext (editing the t4 template), and then in Startup.Auth I have:

        UserManagerFactory = () =>
        {
            var context = new MyContext();

            Database.SetInitializer<MyContext>(new IdentityDbInitializer());

            var userStore = new UserStore<IdentityUser>(context){
                DisposeContext = true
            };

            return new UserManager<IdentityUser>(userStore);
        };

But the problem occurs when I try to log in that I get "cannot contact server". I imagine that is because my UserStore has no way of knowing which are the User tables on my context. I'd hoped this is what the OnModelCreating code would do, but I'm hazy on this. I imagine UserStore is still looking for an "AspNetUsers" table, though I don't know where these names come from. I'm also uneasy about modifying the t4 template for my context - is this the way I'm supposed to derive from IdentityDbContext?

Any help greatly appreciated.

解决方案

Few steps to follow:

  • Install NuGet Package: Microsoft.AspNet.Identity.EntityFramework
  • Add a connection string to your web.config/app.config

Now you have to define your custom Database Context:

public class MyContext : IdentityDbContext
{
    public MyContext()
        : base(<connection string name>)
    {

    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<IdentityUser>()
            .ToTable("Users");

        modelBuilder.Entity<IdentityRole>()
            .ToTable("Roles");

        modelBuilder.Entity<IdentityUserRole>()
            .ToTable("UserRoles");

        modelBuilder.Entity<IdentityUserClaim>()
            .ToTable("UserClaims");

        modelBuilder.Entity<IdentityUserLogin>()
            .ToTable("UserLogins");
    }
}

As you can see I've used DbModelBuilder to map all the entities to a new tables.

  • Open NuGet Package Manager Console
  • Execute command Enable-Migrations

It will create a folder Migrations with the configuration file Configuration.cs.

It should look something like this:

internal sealed class Configuration : DbMigrationsConfiguration<ConsoleApplication1.Models.MyContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(ConsoleApplication1.Models.MyContext context)
    {

    }
}

In the constructor change the property AutomaticMigrationsEnabled to true.

  • Open NuGet Package Manager Console
  • Execute command Update-Database

It should run the script to create the new tables.

You can customize your entities (and Ids) creating custom class for each interface defined.

public class MyUser : IdentityUser<string, MyUserLogin, MyUserRole, MyUserClaim>
{
}

Since you're using Owin you can define your UserStore:

public class MyUserStore: UserStore<MyUser, MyRole, string, MyUserLogin, MyUserRole, MyUserClaim>
{
    public MyUserStore(MyContext context)
        : base(context)
    {
    }
}

and your UserManager implementation:

public class ApplicationUserManager : UserManager<ASPNETIdentity2.Models.MyUser, string>
{
    public ApplicationUserManager(IUserStore<ASPNETIdentity2.Models.MyUser, string> store)
        : base(store)
    {

    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new MyUserStore(context.Get<MyContext>()));

        manager.UserValidator = new UserValidator<MyUser, string>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        manager.PasswordValidator = new PasswordValidator()
        {
            RequiredLength = 5,
            RequireNonLetterOrDigit = false,     // true
            // RequireDigit = true,
            RequireLowercase = false,
            RequireUppercase = false,
        };

        return (manager);
    }
}

And your Owin.Startup should look something like this:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.CreatePerOwinContext(MyContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    }
}

If you want to have a look at a custom implementation you can check my GitHub repository with a simple working solution on ASP.NET MVC.

UPDATE:

There's another project in that solution with a minimal setup; basically you only need to define your context (IdentityDbContext) if you only want to rename your tables.

The project can be found here.

这篇关于尝试在ASP.NET Identity 2.0中更改表名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:55