Invalid object name 'dbo.AspNetUsers' in Asp.NET MVC 5 Entity Framework

爱⌒轻易说出口 提交于 2019-12-17 16:29:13

问题


If you have an existing database, and if you want to include ASP.NET Identity tables to it, you can face this error. Also in the beginning, you may not know how to integrate [AspNetRoles], [AspNetUserClaims], [AspNetUsers], [AspNetUserLogins] tables into your existing database. Although there are a lot of resources about this topic, this answer tries to be short and to the point. You may want to use the Database-First approach in Entity Framework together with the ASP.NET Identity feature of ASP.NET MVC. This is a very short tutorial for dummies. Sorry for my English if it is poor.


回答1:


Here is the shortest integration of Asp.NET Identity tables to your existing database.

1) Open new project or your existing project in Visual Studio (2015 or 2013). Open your Server Explorer and open your DefaultConnection.Find your Identity tables. (In WebConfig file, localDB connectionstring should be active. And your other existing Database's connection string should not be active.) Double Click your [AspNetRoles], [AspNetUserClaims], [AspNetUsers], [AspNetUserLogins] tables. And copy all of their SQL codes.

2) Open your existing database in your SQL Server Management Studio, right click your database and click New Query past here what you copied in 1st part. You will past something like that:

CREATE TABLE [dbo].[AspNetRoles] (
[Id]   NVARCHAR (128) NOT NULL,
[Name] NVARCHAR (256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
CREATE UNIQUE NONCLUSTERED INDEX [RoleNameIndex]
ON [dbo].[AspNetRoles]([Name] ASC);



CREATE TABLE [dbo].[AspNetUsers] (
[Id]                   NVARCHAR (128) NOT NULL,
[Email]                NVARCHAR (256) NULL,
[EmailConfirmed]       BIT            NOT NULL,
[PasswordHash]         NVARCHAR (MAX) NULL,
[SecurityStamp]        NVARCHAR (MAX) NULL,
[PhoneNumber]          NVARCHAR (MAX) NULL,
[PhoneNumberConfirmed] BIT            NOT NULL,
[TwoFactorEnabled]     BIT            NOT NULL,
[LockoutEndDateUtc]    DATETIME       NULL,
[LockoutEnabled]       BIT            NOT NULL,
[AccessFailedCount]    INT            NOT NULL,
[UserName]             NVARCHAR (256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
CREATE UNIQUE NONCLUSTERED INDEX [UserNameIndex]
ON [dbo].[AspNetUsers]([UserName] ASC);


CREATE TABLE [dbo].[AspNetUserRoles] (
[UserId] NVARCHAR (128) NOT NULL,
[RoleId] NVARCHAR (128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED ([UserId] ASC, [RoleId] ASC),
CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY ([RoleId]) REFERENCES [dbo].[AspNetRoles] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[AspNetUsers] ([Id]) ON DELETE CASCADE
 );


GO
CREATE NONCLUSTERED INDEX [IX_UserId]
ON [dbo].[AspNetUserRoles]([UserId] ASC);


GO
CREATE NONCLUSTERED INDEX [IX_RoleId]
ON [dbo].[AspNetUserRoles]([RoleId] ASC);



CREATE TABLE [dbo].[AspNetUserLogins] (
[LoginProvider] NVARCHAR (128) NOT NULL,
[ProviderKey]   NVARCHAR (128) NOT NULL,
[UserId]        NVARCHAR (128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserLogins] PRIMARY KEY CLUSTERED ([LoginProvider] ASC, [ProviderKey] ASC, [UserId] ASC),
CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[AspNetUsers] ([Id]) ON DELETE CASCADE
);


GO
CREATE NONCLUSTERED INDEX [IX_UserId]
ON [dbo].[AspNetUserLogins]([UserId] ASC);



CREATE TABLE [dbo].[AspNetUserClaims] (
[Id]         INT            IDENTITY (1, 1) NOT NULL,
[UserId]     NVARCHAR (128) NOT NULL,
[ClaimType]  NVARCHAR (MAX) NULL,
[ClaimValue] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_dbo.AspNetUserClaims] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[AspNetUsers] ([Id]) ON DELETE CASCADE
);


GO
CREATE NONCLUSTERED INDEX [IX_UserId]
ON [dbo].[AspNetUserClaims]([UserId] ASC);

If you forget the lines which starting with GO, you will exactly see the error which is in Title of this question. Run this query and wait for succesfully creation of tables. Your existing database is now ready for Identity features of Asp.NET MVC 5.

3) Open WebConfig in your Visual Studio. We will change connectionstring here. Write this:

 <add name="DefaultConnection" connectionString="Data Source=YOUR_SERVER_NAME;Initial Catalog=YOUR_DATABASE_NAME;Persist Security Info=True;User ID=YOUR_USER_ID;Password=YOUR_PASSWORD.;MultipleActiveResultSets=True;Application Name=EntityFramework"  providerName="System.Data.SqlClient"/>

Instead of localDB connection string. Which is this:

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

That's all you need to do. Run your project and Register. You can see your new user data in AspNetUsers table, in your existing database.




回答2:


In Visual Studio go to "Tools -> NuGet Package Manager -> Package Manager Console" and in console window (inside Visual Studio) execute "Update-Database" command




回答3:


I go through same issue. some time user create customize class for membership hence asp.net dont create AspNetUsers table
example :

public class Member : IdentityUser
{
    Public int MemberID { get; set; }
    public string Name { get; set; }
    public string Family { get; set; }
    public string Password { get; set; }

}  

in this scenario ASP.NET create Member table and when user want to authenticate,ASP.NET search for AspNetUsers and did not find this table. this problem solved with add TableAttribute in begin of customized class

[Table("AspNetUsers")]
public class Member : IdentityUser
{
    Public int MemberID { get; set; }
    public string Name { get; set; }
    public string Family { get; set; }
    public string Password { get; set; }

}



回答4:


I have faced same problem, Here I was forget to call EnsureCreated(). After calling this method it will create all tables required by Identity.

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
        ...

        // Make sure we have the database
        serviceProvider.GetService<ApplicationDbContext>().Database.EnsureCreated();
}



回答5:


Similar to above you could do this in ConfigureServices

services.Configure<ApplicationDbContext>(o =>
{
  // Make sure the identity database is created
  .o.Database.Migrate();
});
    //     Applies any pending migrations for the context to the database. Will create the
    //     database if it does not already exist.
    //     Note that this API is mutually exclusive with DbContext.Database.EnsureCreated().
    //     EnsureCreated does not use migrations to create the database and therefore the
    //     database that is created cannot be later updated using migrations.


来源:https://stackoverflow.com/questions/38040976/invalid-object-name-dbo-aspnetusers-in-asp-net-mvc-5-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!