Search code examples
c#entity-frameworkwebformsasp.net-identity-2

how to Use Asp.net Identity with DataBase first approach


Hello I am Trying to create Asp.net webforms application with .net 4.5 framework. I have my existing DataBase and I need to work with tha dataBase first approch at the sameTime I need to use ASP.identity. I try to recreate tables which are générated by default with asp.identity In my dataBase and I generate the .edmx file and I change the string connexion name in the

public ApplicationDbContext()
            : base("GoalsDBEntities", throwIfV1Schema: false)
        {
        }

but unfortinately I get the following error

An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code

Additional information: The type of ApplicationUser entity not part of the model for the current context.

Solution

  • To start using ASP.NET Identity I advice the following steps:

    1. Generate a code model from your existing database
    2. On the tables you'd like to use for your Identity implementation inherit from the appropriate classes
    3. Create a migration and apply the changes to your database.

    To enable identity with the files you generated from your database:

    • Inherit the generated context from IdentityDbContext instead of DbContext.
    • Inherit youre user model from IdentityUser

    Based on your situation there are more models of your own you need to inherit from one of the identity classes or you have to add (using code first migrations). See https://msdn.microsoft.com/en-us/library/dn613255%28v=vs.108%29.aspx for more information about the IdentityDbContext.

    Please note that this method requires the needed amount of maintenance when updating your database either with code first migrations or from your database itself. It's not completely impossible but you might have to regenerate your code first model several times OR turn you can turn off the model compatibility check and apply the updates manually to your model. (See: How can I disable model compatibility checking in Entity Framework 4.3?)


    See https://msdn.microsoft.com/en-us/library/jj200620.aspx for infomation about how to generate a code first model from an existing database.

    See https://msdn.microsoft.com/en-us/data/jj591621.aspx for information about enabling migrations on your project.