实体类型 ApplicationUser 不是当前上下文模型的一部分.在项目开始时使用了两个不同的数据库 [英] The entity type ApplicationUser is not part of the model for the current context. Used two different databases at beginning of project

本文介绍了实体类型 ApplicationUser 不是当前上下文模型的一部分.在项目开始时使用了两个不同的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架创建了一个 MVC 4 应用程序,用于向我在 Azure 数据库上托管的数据库读取和写入数据.Azure 数据库应该保留应用程序数据和应用程序的登录数据.

I've created an MVC 4 application using entity framework to read and write data to a database I am hosting on an Azure database. The Azure database was supposed to keep the application data AND the login data for the application.

但是,当我第一次创建应用程序时,我忘记了删除本地计算机的连接字符串.因此,我创建了一个在两个不同位置使用两个不同数据库的应用程序.一个数据库用于应用程序数据 (Azure),另一个数据库用于登录数据 (Local).

However, when I first created the application, I had forgotten to remove the connection string to my local machine. Therefore, I had created an application that used two different databases in two different locations. One database was for the application data (Azure) and the other database was for the login data (Local).

由于我想将此应用程序发布到 Azure,我想将 Azure 数据库用于应用程序和登录信息,并完全排除我本地计算机的数据库.

Since I want to publish this application to Azure, I want to use the Azure database for application AND login information and exclude my local machine's database entirely.

我首先从应用程序的 web.config 文件中删除了本地数据库的连接字符串,从而开始了这个过程.

I've started this process by first removing the connection string for my local database from the application's web.config file.

然后,我更改了 IdentityModels.cs 中的 ApplicationDBContext 类以反映以下更改...

Then, I changed the ApplicationDBContext class in IdentityModels.cs to reflect the changes below...

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("AbacusEntities", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

进行这些更改后,我清理了解决方案,重新构建了它,然后在我的机器上运行它.尝试登录时(此时无论如何都不会成功),我收到此错误实体类型 ApplicationUser 不是当前上下文模型的一部分."在 AccountController.cs 文件中的以下代码上.标有***"的行是调用错误的行.

After making these changes, I've cleaned the solution, rebuilt it, then run it on my machine. When attempting to log in (which would be unsuccessful at this point anyway), I get this error 'The entity type ApplicationUser is not part of the model for the current context.' on the code below in the AccountController.cs file. The line marked with a '***' is the line where the error is called.

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, change to shouldLockout: true
        ***var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

此外,在尝试注册新用户时,我在 AccountController.cs 文件中名为Register"的方法中的以下代码行中遇到相同的错误,这是用户提交用户时的 POST 方法注册.

Also, when attempting to register a new user, I get the same error on the following line of code in the AccountController.cs file in the method named 'Register', which is the POST method for when a user submits a user registration.

var result = await UserManager.CreateAsync(user, model.Password);

另外,请参阅下面 web.config 中的连接字符串.当然,所有敏感信息都已被删除.

Also, please see connection string from web.config below. All sensitive information has, of course, been removed.

add name="AbacusEntities" connectionString="metadata=res://*/Models.AbacusModel.csdl|res://*/Models.AbacusModel.ssdl|res://*/Models.AbacusModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source={Azure server};initial catalog={database name};user id={Database User};password={Password};MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" 

我浏览了许多帖子,但找不到任何有用的信息.我一直在考虑下一步是将我为用户帐户从本地数据库创建的表迁移到 Azure 数据库,但我并不完全相信这会奏效.

I've looked through numerous posts, but I cannot find any useful information. I've been thinking that a next step would be to migrate the tables I've created from my local database for the user accounts to the Azure database, but I'm not completely confident this would work.

我宁愿在 Azure 数据库中生成这些表,并使用 Visual Studio 使用这些表进行身份验证.

What I'd rather do is generate those tables in the Azure database and using visual studio use those for authentication.

最初使用两个不同的数据库登录时,登录过程运行良好,但现在我需要获取要在 Azure 中生成登录数据的表.

When logging in using the two different databases at first, the login process worked just fine, but now I need to get the tables for login data to be generated in Azure.

非常感谢您的帮助,如果您需要任何其他信息,请告诉我!

Your assistance is greatly appreciated and please let me know if you need any additional information!

评论更新:

ApplicationUser 类在 IdentityModel.cs 文件中定义.下面是课程.

The class ApplicationUser is defined in the IdentityModel.cs file. Below is the class.

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

推荐答案

我已尝试按照以下步骤重现您的问题:

I have tried to reproduce your issue according with below steps:

1) 创建 Asp.net MVC 模板,然后注册一个新用户.

1) create Asp.net MVC template, then register a new user.

结果:我们可以在本地数据库中找到用户信息.

Result: We could find user info on local database.

2) 使用实体框架添加带有视图的控制器.并使用 Azure SQL 数据库作为其资源.

2) Add controller with views using Entity Framework. And use Azure SQL database as its resource.

结果:我们会在 web.config 中找到两个连接

Result: we will find two connection in our web.config

3) 删除默认连接字符串

3) Delete default connection string

4) 更改应用程序数据库上下文连接字符串

4) Change Application DB Context connection string

   <add name="jambdbEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=tcp:jambdb.database.windows.net,1433;initial catalog=jambdb;user id=jambor;password=***;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("jambdbEntities", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

经过上述步骤,我的应用程序给我以下错误:

After above steps, My application give me below error:

解决方案:

1) 编辑DefaultConnection"连接字符串

1) Edit 'DefaultConnection' connection string

  <connectionStrings>
    <add name="jambdbEntitiesapplication"   providerName="System.Data.SqlClient" connectionString="Server=tcp:jambdb.database.windows.net,1433;Initial Catalog=jambdb;Persist Security Info=False;User ID=jambor;Password=***;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" />
    <add name="jambdbEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=tcp:jambdb.database.windows.net,1433;initial catalog=jambdb;user id=jambor;password=***;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

2) 修改代码:

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("jambdbEntitiesapplication", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

3) 修改Migrations文件夹下Configuration类中的AutomaticMigrationsEnabled = true;.

3) Modify AutomaticMigrationsEnabled = true; in Configuration class under Migrations folder.

结果如下:

这篇关于实体类型 ApplicationUser 不是当前上下文模型的一部分.在项目开始时使用了两个不同的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆