4

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;
    }
}
1
  • Where is ApplicationUser defined?
    – Eris
    Dec 24, 2016 at 21:54

2 Answers 2

12

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

3
  • This is exactly right. I found this solution on my own yesterday but neglected to post the answer. I will mark your answer as the solution though. I appreciate your help! Thank you! Dec 26, 2016 at 14:04
  • I have a similar result from legacy a legacy WebForms app that is being migrated to Azure. Are you able to explain exactly what was needed? I see you added a connectionstring, but why?
    – coolhand
    May 26, 2017 at 18:49
  • 2
    Great answer but where is the Migrations folder? Is that still a thing?
    – Chris
    Aug 31, 2017 at 17:40
1

Use your database name instead of passing connection string. Check the database name in my example TestDB

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.