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

查看:175
本文介绍了实体类型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),另一个数据库用于登录数据(本地)。

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文件中的注册方法中的以下代码行上获得相同的错误,该方法是用户提交用户注册时的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数据库中生成这些表,并使用可视化工作室来进行认证。

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)更改应用程序DB上下文连接字符串

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)修改

结果如下:

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

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