2014-04-28 17 views
6

To pytanie rozwinęło się, więc zaktualizowałem tytuł.Migrowanie SimpleMembership to Identity 2.0

To był pierwotny tytuł: Identity 2 UserManager.Find rzuca "Nieprawidłowa nazwa obiektu 'dbo.ApplicationUser'" błąd

mam do konwersji z SimpleMembership Tożsamości 2. Mam prowadził skrypt konwersji i refaktoryzował różne pliki do użytku osobistego. Mogę zbudować i uruchomić aplikację, ale przy próbie zalogowania się zostanie zgłoszony błąd "Nieprawidłowy obiekt nazwa" dbo.ApplicationUser "na var user = UserManager.Find (vM.UserName, vM.Password);

Konto Kontroler:

[RequireHttps] 
    [Authorize] 
    public class AccountController : Controller 
    { 
    private readonly IUserService _userService; 

    public UserManager<ApplicationUser> UserManager { get; private set; } 

    public AccountController() 
    : this(new UserService(), new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new MyDb()))) { } 

    public AccountController(IUserService userService, UserManager<ApplicationUser> userManager) 
    { _userService = userService; UserManager = userManager; } 

    // GET: /Account/Login 
    [AllowAnonymous] 
    public ActionResult Login() { return View(); } 

    // POST: /Account/Login 
    [HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public ActionResult Login(LoginVm vM) 
    { 
     if (ModelState.IsValid) 
     { 
     var user = UserManager.Find(vM.UserName, vM.Password); 
     if (user != null) 
     { 
      FormsAuthentication.SetAuthCookie(user.UserName, false); 
      return RedirectToAction("Index", "Home"); 
     } 
     } 
     ModelState.AddModelError("", "The user name or password provided is incorrect."); 

     return View(vM); 
    } 

ApplicationUser:

public class ApplicationUser : IdentityUser 
    { 
    [StringLength(15)] 
    public new string UserName { get; set; } 
    public int AcId { get; set; } 
    public int LcId { get; set; } 
    public string ConfirmationToken { get; set; } 
    public bool IsConfirmed { get; set; } 
    public string PasswordResetToken { get; set; } 
    } 

DbContext.

public class MyDb : IdentityDbContext<ApplicationUser> // DbContext 
    { 
    public MyDb() : base("MyApplicaiton") { } 

    // public virtual DbSet<UserProfiles> Users { get; set; } 
    public virtual DbSet<MyTable> MyTables { get; set; } // properties marked virtual for Mocking override 
    ... 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); 

     modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId); 
     modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id); 
     modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId }); 
    } 
    } 

Dlaczego kierownik użytkownik próbuje uzyskać dostęp do dbo [ApplicationUser] (który nie istnieje) zamiast dbo. [AspNetUsers]?

UPDATE 1: I zdegradowany do Microsoft.AspNet.Identity.EntityFramework 1.0 i Microsoft.AspNet.Identity.Core 1,0 i teraz dostać "Nieprawidłowa nazwa obiektu 'dbo.IdentityUser'" błąd podczas UserManager.Find jest nazywany.

UPDATE 2:

I przeniesieni z powrotem do Identity 2.0 i po prostu zobaczyć, co by się stało, cofnął się i usunięte z bazy danych i regeneruje się go z kodem pierwszy (enable-migracje, update-baza).

Zamiast dodawania tabel Domyślna tożsamość:
AspNetRoles
AspNetClaims
AspNetUserLogins
AspNetUserRoles
AspNetUsers

Dodała te tabele:
dbo.ApplicationUser
dbo.IdentityRole
dbo .IdentityUserClaim
dbo.I dentityUserLogin
dbo.IdentityUserRole

Co wyjaśniłoby, dlaczego szuka on ApplicationUser. Co jest takiego w mojej konfiguracji, że wymusza nazwy zamiast standardowych nazwisk? Prawdopodobnie mógłbym zmienić mój skrypt migracyjny na te nazwy, ale w efekcie otrzymywałbym niestandardowe nazwy tabel, co prowadziłoby do zamieszania. Jak skonfigurować rzeczy, aby uzyskać domyślne nazwy tabel tożsamości?

Odpowiedz

2

Problem z nazwami tabel wynikał z zastąpienia OnModelCreating. Moje wywołania do .Entity < ...>(). HasKey wywoływał te nazwy tabel. Aby uzyskać więcej informacji na temat przesłonięcia, zobacz odpowiedź Olava Nyb0 na: Asp.net Identity Validation Error.I został uaktualniony OnModelCreating do:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    base.OnModelCreating(modelBuilder); 
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); 
} 

My ApplicationUser i migracji skryptu były wzorowane na Identity 1.0 i musiałem je aktualizować tożsamości 2.0.

ApplicationUser:

public class ApplicationUser : IdentityUser 
    { 
    public int AcId { get; set; } 
    public int LcId { get; set; } 
    } 

Oto skrypt migracji skończyło się, że biegnę przeciwko mojej bazy danych SimpleMembership. Nieco oryginalnego pytania, ale włączam to tutaj, aby, mam nadzieję, uratować komuś inne godziny, które spędziłem na szukaniu go.

/****** Object: Table [dbo].[AspNetRoles] Script Date: 4/29/14 ******/ 
SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 

IF OBJECT_ID('dbo.AspNetUserRoles', 'U') IS NOT NULL 
    DROP TABLE [dbo].[AspNetUserRoles] 
GO 
--IF OBJECT_ID('dbo.AspNetUserLogins', 'U') IS NOT NULL 
-- DROP TABLE [dbo].[AspNetUserLogins] 
--GO 
IF OBJECT_ID('dbo.AspNetUserClaims', 'U') IS NOT NULL 
    DROP TABLE [dbo].[AspNetUserClaims] 
GO 
IF OBJECT_ID('dbo.AspNetRoles', 'U') IS NOT NULL 
    DROP TABLE [dbo].[AspNetRoles] 
GO 
IF OBJECT_ID('dbo.AspNetUsers', 'U') IS NOT NULL 
    DROP TABLE [dbo].[AspNetUsers] 
GO 

CREATE TABLE [dbo].[AspNetUsers] (
    [Id]          NVARCHAR (128) NOT NULL, 
    [UserName]        NVARCHAR (15) NULL, 
    [AcId]         INT   NOT NULL, 
    [LcId]         INT   NOT NULL, 
    [Email]         NVARCHAR (256) NULL, 
    [EmailConfirmed]       BIT   DEFAULT ((0)) NULL, 
    [PasswordHash]       NVARCHAR (MAX) NULL, 
    [SecurityStamp]       NVARCHAR (MAX) NULL, 
    [PhoneNumber]        NVARCHAR (MAX) NULL, 
    [PhoneNumberConfirmed]     BIT   DEFAULT ((0)) NULL, 
    [TwoFactorEnabled]      BIT   DEFAULT ((0)) NULL, 
    [LockoutEndDateUtc]      DATETIME  NULL, 
    [Lockoutenabled]       BIT   DEFAULT ((0)) NULL, 
    [AccessFailedCount]      INT   DEFAULT ((0)) NOT NULL, 
    [Discriminator]       NVARCHAR (128) NOT NULL, 
    [CreateDate]        DATETIME  NULL, 
    [ConfirmationToken]      NVARCHAR (128) NULL, 
    [IsConfirmed]        BIT   DEFAULT ((0)) NULL, 
    [LastPasswordFailureDate]     DATETIME  NULL, 
    [PasswordFailuresSinceLastSuccess]  INT   DEFAULT ((0)) NULL, 
    [PasswordChangedDate]      DATETIME  NULL, 
    [PasswordVerificationToken]    NVARCHAR (128) NULL, 
    [PasswordVerificationTokenExpirationDate] DATETIME  NULL, 
    CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC) 
); 
GO 
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 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_RoleId] 
    ON [dbo].[AspNetUserRoles]([RoleId] ASC); 
GO 
CREATE NONCLUSTERED INDEX [IX_UserId] 
    ON [dbo].[AspNetUserRoles]([UserId] ASC); 
GO 
CREATE TABLE [dbo].[AspNetUserLogins] (
    [UserId]  NVARCHAR (128) NOT NULL, 
    [LoginProvider] NVARCHAR (128) NOT NULL, 
    [ProviderKey] NVARCHAR (128) NOT NULL, 
    CONSTRAINT [PK_dbo.AspNetUserLogins] PRIMARY KEY CLUSTERED ([UserId] ASC, [LoginProvider] ASC, [ProviderKey] 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); 
GO 

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

INSERT INTO AspNetUsers(Id, UserName, BaId, OfcId, PasswordHash, SecurityStamp, Discriminator, 
CreateDate, ConfirmationToken, IsConfirmed, LastPasswordFailureDate, PasswordFailuresSinceLastSuccess, 
PasswordChangedDate, PasswordVerificationToken, PasswordVerificationTokenExpirationDate) 
SELECT UserProfile.UserId, UserProfile.UserName, UserProfile.BaId, UserProfile.OfcId, 
webpages_Membership.Password, webpages_Membership.PasswordSalt, 'User', CreateDate, 
ConfirmationToken, IsConfirmed, LastPasswordFailureDate, PasswordFailuresSinceLastSuccess, 
PasswordChangedDate, PasswordVerificationToken, PasswordVerificationTokenExpirationDate 
FROM UserProfile 
LEFT OUTER JOIN webpages_Membership ON UserProfile.UserId = webpages_Membership.UserId 
GO 

INSERT INTO AspNetRoles(Id, Name) 
SELECT RoleId, RoleName 
FROM webpages_Roles 
GO 

INSERT INTO AspNetUserRoles(UserId, RoleId) 
SELECT UserId, RoleId 
FROM webpages_UsersInRoles 
GO 

IF OBJECT_ID('dbo.webpages_OAuthMembership', 'U') IS NOT NULL 
    DROP TABLE [dbo].[webpages_OAuthMembership] 
GO 

IF OBJECT_ID('dbo.webpages_UsersInRoles', 'U') IS NOT NULL 
    DROP TABLE [dbo].[webpages_UsersInRoles] 
GO 
IF OBJECT_ID('dbo.webpages_Roles', 'U') IS NOT NULL 
    DROP TABLE [dbo].[webpages_Roles] 
GO 
IF OBJECT_ID('dbo.UserProfile', 'U') IS NOT NULL 
    DROP TABLE [dbo].[UserProfile] 
GO 
IF OBJECT_ID('dbo.webpages_Membership', 'U') IS NOT NULL 
    DROP TABLE [dbo].[webpages_Membership] 
GO 

--INSERT INTO AspNetUserLogins(UserId, LoginProvider, ProviderKey) 
--SELECT UserId, Provider, ProviderUserId 
--FROM webpages_OAuthMembership 
--GO 

nie używam loginów społeczne stąd komentowania z INSERT INTO AspNetUserLogins (trzeba zrobić, aby utworzyć tabelę choć od Identity 2.0 spodziewa się go).

Tożsamość 2,0 AspNetUsers Tabela ma te pola domyślnie:
[id]
[E]
[EmailConfirmed]
[PasswordHash]
[SecurityStamp]
[PhoneNumber]
[PhoneNumberConfirmed]
[TwoFactorEnabled]
[LockoutEndDateUtc]
[LockoutEnabled]
[AccessFailedCount]
[nazwa_użytkownika]

ja wciąż eksperymentuje, należy kierować się zdrowym rozsądkiem, co trzeba migrować z tabeli webpages_Membership. W tym momencie mogę się zalogować.

UPDATE:

W moim ApplicationUser miałem nadpisane nazwy użytkownika, aby skrócić pole. NIE rób tego, spowoduje to błąd uwierzytelniania. Możesz kontrolować długość pola w skrypcie migracji. Usunąłem nadpisanie w OP. Dla bardziej zobaczyć User.IsInRole failing.

ApplicationUser:

public class ApplicationUser : IdentityUser 
    { 
    // [StringLength(15)] // do not override UserName, will cause authentication error. 
    // public new string UserName { get; set; } 
    public int AcId { get; set; } 
    public int LcId { get; set; } 
    // public string ConfirmationToken { get; set; } // Depends on your app if you need to migrate these fields 
    // public bool IsConfirmed { get; set; } 
    // public string PasswordResetToken { get; set; } 
    }