Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The entity type ApplicationUser is not part of the model for the current context. Used two different databases at beginning of project

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.

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).

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.

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

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();
    }
}

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);
        }
    }

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);

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" 

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.

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

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!

Update from comments:

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;
    }
}
like image 293
TheRedCameron Avatar asked Dec 14 '22 01:12

TheRedCameron


1 Answers

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

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

Result: We could find user info on local database.

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

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

3) Delete default connection string

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:

enter image description here

Solution:

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) Modify the code:

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

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

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

Here is the result:

enter image description here

like image 102
Jambor - MSFT Avatar answered Jan 04 '23 22:01

Jambor - MSFT