ASP.NET /Identity错误:实体类型ApplicationUser不是当前上下文的模型的一部分

时间:2014-03-23 15:19:53

标签: mysql asp.net entity-framework asp.net-identity

Move ASP.NET Identity store to EF Sql database zoidbergi描述的问题类似于我遇到的问题,但未完全回答。我在尝试从内置的.mdf数据库迁移到MySQL时收到上述错误。我使用的是Database-First方法,并且已经从底层的Mysql数据库中成功创建了实体模型。

无论是否重新创建asp.net标识数据表,只要访问用户管理器,应用程序就会阻塞:

The entity type ApplicationUser is not part of the model for the current context.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: The entity type ApplicationUser is not part of the model for the current context.

Source Error:  

Line 65:             ' Create a local login before signing in the user
Line 66:             Dim user = New ApplicationUser() With {.UserName = model.UserName}
**Line 67:             Dim result = Await UserManager.CreateAsync(User, model.Password)**
Line 68:             If result.Succeeded Then
Line 69:                 Await SignInAsync(User, isPersistent:=False)

我已将ApplicationDBContext指向我的DbContext模型:

Public Class ApplicationDbContext
    Inherits IdentityDbContext(Of ApplicationUser)
    Public Sub New()
        MyBase.New("IMSEntities")
    End Sub
End Class
谷歌搜索倾向于找到已经放弃并编码自己的安全提供商的人 - 如果可能的话,我想使用标准安全提供商。折流板!

2 个答案:

答案 0 :(得分:28)

(INELEGANT?)解决方案:

我观看了Alexander Schmidt撰写的这段精彩视频https://www.youtube.com/watch?v=elfqejow5hM,并在33:00作者发现连接字符串不应该是EF连接字符串(使用EF提供程序),但应该是一个vanilla MYSQL / SQLServer连接字符串专门为安全设置,即:

<add name="IMSSecurityEntities" connectionString="data source=localhost;database=mydb;Uid=id;Pwd=password;" providerName="mysql.data.mysqlclient"/>

同样地,身份模型应该调整为:

Public Class ApplicationDbContext
    Inherits IdentityDbContext(Of ApplicationUser)
    Public Sub New()
        MyBase.New("IMSSecurityEntities")
    End Sub

这使我对通过ORM访问安全实体感到紧张 - 但我想可能是设计因此可能没有损失。

答案 1 :(得分:1)

在我的例子中,它是连接字符串的providerName属性。我使用了Database First生成的连接字符串的副本,该字符串使用System.Data.EntityClient,而普通连接字符串(到SQL Server)使用System.Data.SqlClient。所以我改变了这个

<add name="DefaultConnection" connectionString="..." System.Data.EntityClient"/>

到这个

<add name="DefaultConnection" connectionString="..." System.Data.SqlClient"/>