ASP。NET身份与EF数据库第一MVC5

时间:2022-09-18 08:28:41

Is it possible to use the new Asp.net Identity with Database First and EDMX? Or only with code first?

是否可以使用新的Asp.net身份与数据库和EDMX?还是只有代码优先?

Here's what I did:

这是我所做的:

1) I made a new MVC5 Project and had the new Identity create the new User and Roles tables in my database.

1)我做了一个新的MVC5项目,让新的标识在我的数据库中创建新的用户和角色表。

2) I then opened my Database First EDMX file and dragged in the new Identity Users table since I have other tables that relate to it.

2)然后,我打开数据库的第一个EDMX文件,并将其拖放到新的Identity Users表中,因为我有与之相关的其他表。

3) Upon saving the EDMX, the Database First POCO generator will auto create a User class. However, UserManager and RoleManager expects a User class inheriting from the new Identity namespace (Microsoft.AspNet.Identity.IUser), so using the POCO User class won't work.

3)保存EDMX后,数据库First POCO生成器将自动创建一个用户类。然而,UserManager和RoleManager期望用户类继承新的标识名称空间(Microsoft.AspNet.Identity.IUser . User),因此使用POCO用户类是行不通的。

I guess a possible solution is to edit my POCO Generation Classes to have my User class inherit from IUser?

我想一个可能的解决方案是编辑POCO生成类,使我的User类继承IUser类?

Or is ASP.NET Identity only compatible with Code First Design?

或者是ASP。NET标识只与代码优先设计兼容?

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Update: Following Anders Abel's suggestion below, this is what I did. It work's, but I'm wondering if there is a more elegant solution.

更新:以下是安德斯·阿贝尔的建议,我就是这么做的。这是可行的,但我想知道是否有更好的解决方案。

1) I extended my entity User class by creating a partial class within the same namespace as my auto generated entities.

1)通过在与自动生成的实体相同的名称空间中创建部分类来扩展我的实体用户类。

namespace MVC5.DBFirst.Entity
{
    public partial class AspNetUser : IdentityUser
    {
    }
}

2) I changed my DataContext to inherit from IdentityDBContext instead of DBContext. Note that every time you update your EDMX and regenerate the DBContext and Entity classes, you'll have to set this back to this.

2)我将DataContext改为从IdentityDBContext继承,而不是从DBContext继承。注意,每次更新您的EDMX并重新生成DBContext和实体类时,都必须将其设置为这个。

 public partial class MVC5Test_DBEntities : IdentityDbContext<AspNetUser>  //DbContext

3) Within your auto generated User entity class, you must add the override keyword to the following 4 fields or comment these fields out since they are inherited from IdentityUser (Step 1). Note that every time you update your EDMX and regenerate the DBContext and Entity classes, you'll have to set this back to this.

3)在你的自动生成用户实体类,您必须添加覆盖关键字如下4个字段或这些字段注释掉因为它们继承IdentityUser(步骤1)。注意,每次你更新你的EDMX和再生DBContext和实体类,您必须设置这个回到这。

    override public string Id { get; set; }
    override public string UserName { get; set; }
    override public string PasswordHash { get; set; }
    override public string SecurityStamp { get; set; }

9 个解决方案

#1


15  

It should be possible to use the identity system with POCO and Database First, but you'll have to make a couple of tweaks:

应该可以先使用POCO和数据库的身份系统,但您需要做一些调整:

  1. Update the .tt-file for POCO generation to make the entity classes partial. That will make it possible for you to supply additional implementation in a separate file.
  2. 更新为POCO生成的.tt文件,使实体类成为局部的。这将使您能够在单独的文件中提供其他实现。
  3. Make a partial implementation of the User class in another file
  4. 在另一个文件中实现用户类的部分实现

 

 

partial User : IUser
{
}

That will make the User class implement the right interface, without touching the actual generated files (editing generated files is always a bad idea).

这将使User类实现正确的接口,而不涉及实际生成的文件(编辑生成的文件总是一个坏主意)。

#2


13  

My steps are very similar but I wanted to share.

我的步骤非常相似,但我想分享。

1) Create a new MVC5 project

1)创建一个新的MVC5项目。

2) Create a new Model.edmx. Even if it's a new database and has no tables.

2)创建一个新的模型。即使它是一个新的数据库并且没有表。

3) Edit web.config and replace this generated connectionstring:

3)编辑web。配置并替换生成的connectionstring:

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-SSFInventory-20140521115734.mdf;Initial Catalog=aspnet-SSFInventory-20140521115734;Integrated Security=True" providerName="System.Data.SqlClient" />

with this connectionstring:

用这个connectionstring:

<add name="DefaultConnection" connectionString="Data Source=.\SQLExpress;database=SSFInventory;integrated security=true;" providerName="System.Data.SqlClient" />

Afterwards, build and run the application. Register a user and then the tables will be created.

然后,构建并运行应用程序。注册一个用户,然后将创建表。

#3


10  

EDIT: ASP.NET Identity with EF Database First for MVC5 CodePlex Project Template.

编辑:ASP。MVC5 CodePlex项目模板上的EF数据库。


I wanted to use an existing database and create relationships with ApplicationUser. This is how I did it using SQL Server but the same idea would probably work with any DB.

我希望使用现有的数据库,并与ApplicationUser建立关系。这是我使用SQL Server完成的,但同样的想法可能适用于任何DB。

  1. Create an MVC Project
  2. 创建一个MVC项目
  3. Open the DB listed under the DefaultConnection in Web.config. It will be called (aspnet-[timestamp] or something like that.)
  4. 在Web.config中打开默认连接下列出的DB。它将被调用(aspnet-[时间戳]或类似的东西)。
  5. Script the database tables.
  6. 脚本的数据库表。
  7. Insert the scripted tables into existing database in SQL Server Management Studio.
  8. 将脚本化的表插入到SQL Server Management Studio中的现有数据库中。
  9. Customize and add relationships to ApplicationUser (if necessary).
  10. 自定义并向ApplicationUser添加关系(如果需要)。
  11. Create new Web Project > MVC > DB First Project > Import DB with EF ... Excluding the Identity Classes you inserted.
  12. 创建新的Web项目> MVC > DB First Project > Import DB with EF…排除插入的标识类。
  13. In IdentityModels.cs change the ApplicationDbContext :base("DefaltConnection") to use your project's DbContext.
  14. 在IdentityModels。cs更改ApplicationDbContext:base(“DefaltConnection”)以使用项目的DbContext。

Edit: Asp.Net Identity Class Diagram ASP。NET身份与EF数据库第一MVC5

编辑:Asp。净身份类图

#4


8  

IdentityUser is worthless here because it's the code-first object used by the UserStore for authentication. After defining my own User object, I implemented a partial class that implements IUser which is used by the UserManager class. I wanted my Ids to be int instead of string so I just return the UserID's toString(). Similarly I wanted n in Username to be uncapitalized.

IdentityUser在这里毫无用处,因为它是UserStore用于身份验证的代码优先对象。在定义了自己的用户对象之后,我实现了一个部分类,它实现了UserManager类使用的IUser。我希望我的id是int型而不是string,所以我只返回UserID的toString()。类似地,我希望用户名中的n是无资本化的。

public partial class User : IUser
{

    public string Id
    {
        get { return this.UserID.ToString(); }
    }

    public string UserName
    {
        get
        {
            return this.Username;
        }
        set
        {
            this.Username = value;
        }
    }
}

You by no means need IUser. It's only an interface used by the UserManager. So if you want to define a different "IUser" you would have to rewrite this class to use your own implementation.

你根本不需要IUser。它只是UserManager使用的一个接口。因此,如果您想定义一个不同的“IUser”,您将不得不重写这个类以使用您自己的实现。

public class UserManager<TUser> : IDisposable where TUser: IUser

You now write your own UserStore which handles all of the storage of users, claims, roles, etc. Implement the interfaces of everything that the code-first UserStore does and change where TUser : IdentityUser to where TUser : User where "User" is your entity object

现在,您编写自己的UserStore,它处理用户、声明、角色等的所有存储。实现代码第一个UserStore所做的所有事情的接口,并将TUser: IdentityUser的位置更改为TUser: User(用户)是您的实体对象。

public class MyUserStore<TUser> : IUserLoginStore<TUser>, IUserClaimStore<TUser>, IUserRoleStore<TUser>, IUserPasswordStore<TUser>, IUserSecurityStampStore<TUser>, IUserStore<TUser>, IDisposable where TUser : User
{
    private readonly MyAppEntities _context;
    public MyUserStore(MyAppEntities dbContext)
    { 
        _context = dbContext; 
    }

    //Interface definitions
}

Here are a couple examples on some of the interface implementations

下面是一些接口实现的示例

async Task IUserStore<TUser>.CreateAsync(TUser user)
{
    user.CreatedDate = DateTime.Now;
    _context.Users.Add(user);
    await _context.SaveChangesAsync();
}

async Task IUserStore<TUser>.DeleteAsync(TUser user)
{
    _context.Users.Remove(user);
    await _context.SaveChangesAsync();
}

Using the MVC 5 template, I changed the AccountController to look like this.

使用MVC 5模板,我将AccountController更改为如下所示。

public AccountController()
        : this(new UserManager<User>(new MyUserStore<User>(new MyAppEntities())))
{
}

Now logging in should work with your own tables.

现在登录应该可以使用您自己的表。

#5


3  

Take a look at this project on GitHub: https://github.com/KriaSoft/AspNet.Identity

看看GitHub上的这个项目:https://github.com/KriaSoft/AspNet.Identity

Which includes:

其中包括:

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

ASP。NET身份与EF数据库第一MVC5

Also see: How to create Database-First provider for ADO.NET Identity

另请参见:如何为ADO创建数据库优先提供程序。净的身份

#6


2  

I spent several hours working through this and finally found a solution which I have shared on my blog here. Basically, you need to do everything said in stink's answer but with one additional thing: ensuring Identity Framework has a specific SQL-Client connection string on top of the Entity Framework connection string used for your application entities.

我花了几个小时研究这个问题,最终找到了一个解决方案,我在这里的博客上分享了这个方案。基本上,您需要做stink的回答中提到的所有事情,但还有一件事:确保Identity框架在用于应用程序实体的实体框架连接字符串之上具有特定的SQL-Client连接字符串。

In summary, your application will use a connection string for Identity Framework and another for your application entities. Each connection string is of a different type. Read my blog post for a full tutorial.

总之,应用程序将使用标识框架的连接字符串和应用程序实体的连接字符串。每个连接字符串都是不同的类型。阅读我的博客文章,获得完整的教程。

#7


2  

Good question.

好问题。

I'm more of a database-first person. The code first paradigm seems to loosey-goosey to me, and the "migrations" seem too error prone.

我更像是一个数据库第一的人。代码优先范式对我来说似乎很容易出错,而“迁移”似乎太容易出错。

I wanted to customize the aspnet identity schema, and not be bothered with migrations. I'm well versed with Visual Studio database projects (sqlpackage, data-dude) and how it does a pretty good job at upgrading schemas.

我想要定制aspnet标识模式,而不需要为迁移操心。我精通Visual Studio数据库项目(sqlpackage, data-dude),以及它在升级模式方面的表现。

My simplistic solution is to:

我简单的解决办法是:

1) Create a database project that mirrors the aspnet identity schema 2) use the output of this project (.dacpac) as a project resource 3) deploy the .dacpac when needed

1)创建一个数据库项目,该项目反映了aspnet身份模式2)使用该项目的输出(.dacpac)作为项目资源3)在需要时部署.dacpac。

For MVC5, modifying the ApplicationDbContext class seems to get this going...

对于MVC5,修改ApplicationDbContext类似乎可以使其继续……

1) Implement IDatabaseInitializer

1)实现IDatabaseInitializer

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDatabaseInitializer<ApplicationDbContext> { ... }

public类ApplicationDbContext: IdentityDbContext , IDatabaseInitializer {…}

2) In the constructor, signal that this class will implement database initialization:

2)在构造函数中,表示该类将实现数据库初始化:

Database.SetInitializer<ApplicationDbContext>(this);

Database.SetInitializer < ApplicationDbContext >();

3) Implement InitializeDatabase:

3)实现InitializeDatabase:

Here, I chose to use DacFX and deploy my .dacpac

在这里,我选择使用DacFX并部署我的.dacpac

    void IDatabaseInitializer<ApplicationDbContext>.InitializeDatabase(ApplicationDbContext context)
    {
        using (var ms = new MemoryStream(Resources.Binaries.MainSchema))
        {
            using (var package = DacPackage.Load(ms, DacSchemaModelStorageType.Memory))
            {
                DacServices services = new DacServices(Database.Connection.ConnectionString);
                var options = new DacDeployOptions
                {
                    VerifyDeployment = true,
                    BackupDatabaseBeforeChanges = true,
                    BlockOnPossibleDataLoss = false,
                    CreateNewDatabase = false,
                    DropIndexesNotInSource = true,
                    IgnoreComments = true,

                };
                services.Deploy(package, Database.Connection.Database, true, options);
            }
        }
    }

#8


1  

We have a Entity Model DLL project where we keep our model class. We also keep a Database Project with all of database scripts. My approach was as follows

我们有一个实体模型DLL项目,我们在其中保存模型类。我们还保留了一个包含所有数据库脚本的数据库项目。我的方法如下

1) Create your own project that has the EDMX using database first

1)创建您自己的项目,该项目首先使用EDMX数据库

2) Script the tables in your db, I used VS2013 connected to localDB (Data Connections) and copied the script to database project, add any custom columns, e.g. BirthDate [DATE] not null

2)为数据库中的表编写脚本,使用连接到localDB(数据连接)的VS2013,将脚本复制到数据库项目中,添加任何自定义列,例如BirthDate [DATE] not null

3) Deploy the database

3)部署数据库

4) Update the Model (EDMX) project Add to the Model project

4)更新模型(EDMX)项目添加到模型项目

5) Add any custom columns to the application class

5)向应用程序类添加任何自定义列

public class ApplicationUser : IdentityUser
{
    public DateTime BirthDate { get; set; }
}

In the MVC project AccountController added the following:

在MVC项目AccountController中增加了以下内容:

The Identity Provider want a SQL Connection String for it to work, to keep only 1 connection string for the database, extract the provider string from EF connection string

标识提供程序希望SQL连接字符串能够正常工作,为了仅保留数据库的一个连接字符串,从EF连接字符串中提取提供程序字符串

public AccountController()
{
   var connection = ConfigurationManager.ConnectionStrings["Entities"];
   var entityConnectionString = new EntityConnectionStringBuilder(connection.ConnectionString);
        UserManager =
            new UserManager<ApplicationUser>(
                new UserStore<ApplicationUser>(
                    new ApplicationDbContext(entityConnectionString.ProviderConnectionString)));
}

#9


1  

I found that @JoshYates1980 does have the simplest answer.

我发现@JoshYates1980确实有最简单的答案。

After a series trials and errors I did what Josh suggested and replaced the connectionString with my generated DB connection string. what I was confused about originally was the following post:

在一系列测试和错误之后,我按照Josh的建议做了,用生成的DB连接字符串替换了connectionString。我最初困惑的是下面这篇文章:

How to add ASP.NET MVC5 Identity Authentication to existing database

如何添加ASP。NET MVC5对现有数据库的身份验证

Where the accepted answer from @Win stated to change the ApplicationDbContext() connection name. This is a little vague if you are using Entity and a Database/Model first approach where the database connection string is generated and added to the Web.config file.

其中,@Win给出的已接受答案表示要更改ApplicationDbContext()连接名。如果您使用的是实体和数据库/模型第一方法,即生成数据库连接字符串并将其添加到Web中,那么这有点模糊。配置文件。

The ApplicationDbContext() connection name is mapped to the default connection in theWeb.config file. Therefore, Josh's method works best, but to make the ApplicationDbContext() more readable I would suggest changing the name to your database name as @Win originally posted, making sure to change the connectionString for the "DefaultConnection" in the Web.config and comment out and/or remov the Entity generated database include.

ApplicationDbContext()连接名映射到web中的默认连接。配置文件。因此,Josh的方法是最有效的,但是为了使ApplicationDbContext()更具可读性,我建议将您的数据库名改为@Win,确保更改Web中的“DefaultConnection”的connectionString。配置和注释并/或删除实体生成的数据库包含的内容。

Code Examples:

代码示例:

#1


15  

It should be possible to use the identity system with POCO and Database First, but you'll have to make a couple of tweaks:

应该可以先使用POCO和数据库的身份系统,但您需要做一些调整:

  1. Update the .tt-file for POCO generation to make the entity classes partial. That will make it possible for you to supply additional implementation in a separate file.
  2. 更新为POCO生成的.tt文件,使实体类成为局部的。这将使您能够在单独的文件中提供其他实现。
  3. Make a partial implementation of the User class in another file
  4. 在另一个文件中实现用户类的部分实现

 

 

partial User : IUser
{
}

That will make the User class implement the right interface, without touching the actual generated files (editing generated files is always a bad idea).

这将使User类实现正确的接口,而不涉及实际生成的文件(编辑生成的文件总是一个坏主意)。

#2


13  

My steps are very similar but I wanted to share.

我的步骤非常相似,但我想分享。

1) Create a new MVC5 project

1)创建一个新的MVC5项目。

2) Create a new Model.edmx. Even if it's a new database and has no tables.

2)创建一个新的模型。即使它是一个新的数据库并且没有表。

3) Edit web.config and replace this generated connectionstring:

3)编辑web。配置并替换生成的connectionstring:

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-SSFInventory-20140521115734.mdf;Initial Catalog=aspnet-SSFInventory-20140521115734;Integrated Security=True" providerName="System.Data.SqlClient" />

with this connectionstring:

用这个connectionstring:

<add name="DefaultConnection" connectionString="Data Source=.\SQLExpress;database=SSFInventory;integrated security=true;" providerName="System.Data.SqlClient" />

Afterwards, build and run the application. Register a user and then the tables will be created.

然后,构建并运行应用程序。注册一个用户,然后将创建表。

#3


10  

EDIT: ASP.NET Identity with EF Database First for MVC5 CodePlex Project Template.

编辑:ASP。MVC5 CodePlex项目模板上的EF数据库。


I wanted to use an existing database and create relationships with ApplicationUser. This is how I did it using SQL Server but the same idea would probably work with any DB.

我希望使用现有的数据库,并与ApplicationUser建立关系。这是我使用SQL Server完成的,但同样的想法可能适用于任何DB。

  1. Create an MVC Project
  2. 创建一个MVC项目
  3. Open the DB listed under the DefaultConnection in Web.config. It will be called (aspnet-[timestamp] or something like that.)
  4. 在Web.config中打开默认连接下列出的DB。它将被调用(aspnet-[时间戳]或类似的东西)。
  5. Script the database tables.
  6. 脚本的数据库表。
  7. Insert the scripted tables into existing database in SQL Server Management Studio.
  8. 将脚本化的表插入到SQL Server Management Studio中的现有数据库中。
  9. Customize and add relationships to ApplicationUser (if necessary).
  10. 自定义并向ApplicationUser添加关系(如果需要)。
  11. Create new Web Project > MVC > DB First Project > Import DB with EF ... Excluding the Identity Classes you inserted.
  12. 创建新的Web项目> MVC > DB First Project > Import DB with EF…排除插入的标识类。
  13. In IdentityModels.cs change the ApplicationDbContext :base("DefaltConnection") to use your project's DbContext.
  14. 在IdentityModels。cs更改ApplicationDbContext:base(“DefaltConnection”)以使用项目的DbContext。

Edit: Asp.Net Identity Class Diagram ASP。NET身份与EF数据库第一MVC5

编辑:Asp。净身份类图

#4


8  

IdentityUser is worthless here because it's the code-first object used by the UserStore for authentication. After defining my own User object, I implemented a partial class that implements IUser which is used by the UserManager class. I wanted my Ids to be int instead of string so I just return the UserID's toString(). Similarly I wanted n in Username to be uncapitalized.

IdentityUser在这里毫无用处,因为它是UserStore用于身份验证的代码优先对象。在定义了自己的用户对象之后,我实现了一个部分类,它实现了UserManager类使用的IUser。我希望我的id是int型而不是string,所以我只返回UserID的toString()。类似地,我希望用户名中的n是无资本化的。

public partial class User : IUser
{

    public string Id
    {
        get { return this.UserID.ToString(); }
    }

    public string UserName
    {
        get
        {
            return this.Username;
        }
        set
        {
            this.Username = value;
        }
    }
}

You by no means need IUser. It's only an interface used by the UserManager. So if you want to define a different "IUser" you would have to rewrite this class to use your own implementation.

你根本不需要IUser。它只是UserManager使用的一个接口。因此,如果您想定义一个不同的“IUser”,您将不得不重写这个类以使用您自己的实现。

public class UserManager<TUser> : IDisposable where TUser: IUser

You now write your own UserStore which handles all of the storage of users, claims, roles, etc. Implement the interfaces of everything that the code-first UserStore does and change where TUser : IdentityUser to where TUser : User where "User" is your entity object

现在,您编写自己的UserStore,它处理用户、声明、角色等的所有存储。实现代码第一个UserStore所做的所有事情的接口,并将TUser: IdentityUser的位置更改为TUser: User(用户)是您的实体对象。

public class MyUserStore<TUser> : IUserLoginStore<TUser>, IUserClaimStore<TUser>, IUserRoleStore<TUser>, IUserPasswordStore<TUser>, IUserSecurityStampStore<TUser>, IUserStore<TUser>, IDisposable where TUser : User
{
    private readonly MyAppEntities _context;
    public MyUserStore(MyAppEntities dbContext)
    { 
        _context = dbContext; 
    }

    //Interface definitions
}

Here are a couple examples on some of the interface implementations

下面是一些接口实现的示例

async Task IUserStore<TUser>.CreateAsync(TUser user)
{
    user.CreatedDate = DateTime.Now;
    _context.Users.Add(user);
    await _context.SaveChangesAsync();
}

async Task IUserStore<TUser>.DeleteAsync(TUser user)
{
    _context.Users.Remove(user);
    await _context.SaveChangesAsync();
}

Using the MVC 5 template, I changed the AccountController to look like this.

使用MVC 5模板,我将AccountController更改为如下所示。

public AccountController()
        : this(new UserManager<User>(new MyUserStore<User>(new MyAppEntities())))
{
}

Now logging in should work with your own tables.

现在登录应该可以使用您自己的表。

#5


3  

Take a look at this project on GitHub: https://github.com/KriaSoft/AspNet.Identity

看看GitHub上的这个项目:https://github.com/KriaSoft/AspNet.Identity

Which includes:

其中包括:

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

ASP。NET身份与EF数据库第一MVC5

Also see: How to create Database-First provider for ADO.NET Identity

另请参见:如何为ADO创建数据库优先提供程序。净的身份

#6


2  

I spent several hours working through this and finally found a solution which I have shared on my blog here. Basically, you need to do everything said in stink's answer but with one additional thing: ensuring Identity Framework has a specific SQL-Client connection string on top of the Entity Framework connection string used for your application entities.

我花了几个小时研究这个问题,最终找到了一个解决方案,我在这里的博客上分享了这个方案。基本上,您需要做stink的回答中提到的所有事情,但还有一件事:确保Identity框架在用于应用程序实体的实体框架连接字符串之上具有特定的SQL-Client连接字符串。

In summary, your application will use a connection string for Identity Framework and another for your application entities. Each connection string is of a different type. Read my blog post for a full tutorial.

总之,应用程序将使用标识框架的连接字符串和应用程序实体的连接字符串。每个连接字符串都是不同的类型。阅读我的博客文章,获得完整的教程。

#7


2  

Good question.

好问题。

I'm more of a database-first person. The code first paradigm seems to loosey-goosey to me, and the "migrations" seem too error prone.

我更像是一个数据库第一的人。代码优先范式对我来说似乎很容易出错,而“迁移”似乎太容易出错。

I wanted to customize the aspnet identity schema, and not be bothered with migrations. I'm well versed with Visual Studio database projects (sqlpackage, data-dude) and how it does a pretty good job at upgrading schemas.

我想要定制aspnet标识模式,而不需要为迁移操心。我精通Visual Studio数据库项目(sqlpackage, data-dude),以及它在升级模式方面的表现。

My simplistic solution is to:

我简单的解决办法是:

1) Create a database project that mirrors the aspnet identity schema 2) use the output of this project (.dacpac) as a project resource 3) deploy the .dacpac when needed

1)创建一个数据库项目,该项目反映了aspnet身份模式2)使用该项目的输出(.dacpac)作为项目资源3)在需要时部署.dacpac。

For MVC5, modifying the ApplicationDbContext class seems to get this going...

对于MVC5,修改ApplicationDbContext类似乎可以使其继续……

1) Implement IDatabaseInitializer

1)实现IDatabaseInitializer

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDatabaseInitializer<ApplicationDbContext> { ... }

public类ApplicationDbContext: IdentityDbContext , IDatabaseInitializer {…}

2) In the constructor, signal that this class will implement database initialization:

2)在构造函数中,表示该类将实现数据库初始化:

Database.SetInitializer<ApplicationDbContext>(this);

Database.SetInitializer < ApplicationDbContext >();

3) Implement InitializeDatabase:

3)实现InitializeDatabase:

Here, I chose to use DacFX and deploy my .dacpac

在这里,我选择使用DacFX并部署我的.dacpac

    void IDatabaseInitializer<ApplicationDbContext>.InitializeDatabase(ApplicationDbContext context)
    {
        using (var ms = new MemoryStream(Resources.Binaries.MainSchema))
        {
            using (var package = DacPackage.Load(ms, DacSchemaModelStorageType.Memory))
            {
                DacServices services = new DacServices(Database.Connection.ConnectionString);
                var options = new DacDeployOptions
                {
                    VerifyDeployment = true,
                    BackupDatabaseBeforeChanges = true,
                    BlockOnPossibleDataLoss = false,
                    CreateNewDatabase = false,
                    DropIndexesNotInSource = true,
                    IgnoreComments = true,

                };
                services.Deploy(package, Database.Connection.Database, true, options);
            }
        }
    }

#8


1  

We have a Entity Model DLL project where we keep our model class. We also keep a Database Project with all of database scripts. My approach was as follows

我们有一个实体模型DLL项目,我们在其中保存模型类。我们还保留了一个包含所有数据库脚本的数据库项目。我的方法如下

1) Create your own project that has the EDMX using database first

1)创建您自己的项目,该项目首先使用EDMX数据库

2) Script the tables in your db, I used VS2013 connected to localDB (Data Connections) and copied the script to database project, add any custom columns, e.g. BirthDate [DATE] not null

2)为数据库中的表编写脚本,使用连接到localDB(数据连接)的VS2013,将脚本复制到数据库项目中,添加任何自定义列,例如BirthDate [DATE] not null

3) Deploy the database

3)部署数据库

4) Update the Model (EDMX) project Add to the Model project

4)更新模型(EDMX)项目添加到模型项目

5) Add any custom columns to the application class

5)向应用程序类添加任何自定义列

public class ApplicationUser : IdentityUser
{
    public DateTime BirthDate { get; set; }
}

In the MVC project AccountController added the following:

在MVC项目AccountController中增加了以下内容:

The Identity Provider want a SQL Connection String for it to work, to keep only 1 connection string for the database, extract the provider string from EF connection string

标识提供程序希望SQL连接字符串能够正常工作,为了仅保留数据库的一个连接字符串,从EF连接字符串中提取提供程序字符串

public AccountController()
{
   var connection = ConfigurationManager.ConnectionStrings["Entities"];
   var entityConnectionString = new EntityConnectionStringBuilder(connection.ConnectionString);
        UserManager =
            new UserManager<ApplicationUser>(
                new UserStore<ApplicationUser>(
                    new ApplicationDbContext(entityConnectionString.ProviderConnectionString)));
}

#9


1  

I found that @JoshYates1980 does have the simplest answer.

我发现@JoshYates1980确实有最简单的答案。

After a series trials and errors I did what Josh suggested and replaced the connectionString with my generated DB connection string. what I was confused about originally was the following post:

在一系列测试和错误之后,我按照Josh的建议做了,用生成的DB连接字符串替换了connectionString。我最初困惑的是下面这篇文章:

How to add ASP.NET MVC5 Identity Authentication to existing database

如何添加ASP。NET MVC5对现有数据库的身份验证

Where the accepted answer from @Win stated to change the ApplicationDbContext() connection name. This is a little vague if you are using Entity and a Database/Model first approach where the database connection string is generated and added to the Web.config file.

其中,@Win给出的已接受答案表示要更改ApplicationDbContext()连接名。如果您使用的是实体和数据库/模型第一方法,即生成数据库连接字符串并将其添加到Web中,那么这有点模糊。配置文件。

The ApplicationDbContext() connection name is mapped to the default connection in theWeb.config file. Therefore, Josh's method works best, but to make the ApplicationDbContext() more readable I would suggest changing the name to your database name as @Win originally posted, making sure to change the connectionString for the "DefaultConnection" in the Web.config and comment out and/or remov the Entity generated database include.

ApplicationDbContext()连接名映射到web中的默认连接。配置文件。因此,Josh的方法是最有效的,但是为了使ApplicationDbContext()更具可读性,我建议将您的数据库名改为@Win,确保更改Web中的“DefaultConnection”的connectionString。配置和注释并/或删除实体生成的数据库包含的内容。

Code Examples:

代码示例: