The Entity Type Applicationuser Is Not Part of the Model for the Current Context

The entity type ApplicationUser is not part of the model for the current context

for me it seems to miss a context instanciation:

UserManagerFactory = () => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());

should be

UserManagerFactory = () => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

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

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="data source=tcp:jambdb.database.windows.net,1433;initial catalog=jambdb;user id=jambor;password=***;MultipleActiveResultSets=True;App=EntityFramework"" 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:

Sample Image

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="data source=tcp:jambdb.database.windows.net,1433;initial catalog=jambdb;user id=jambor;password=***;MultipleActiveResultSets=True;App=EntityFramework"" 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:

Sample Image

entity type ApplicationUser is not part of the model for the current context

where is your ApplicationUserManager Method

you need to configure Application UserManager Like this by passing DbContext

public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<EducationContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};

// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};

// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;

// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}

most important is to write this line(First Line in Create method)

var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<EducationContext>()));

The entity type ApplicationUser is not part of the model for the current context Asp.Net MVC

Point 1 : I have seen in your web.config you are having two connections string but both are using same connection and same db so you don't require second one . Remove the below line from your web.config

<add name="DefaultConnection" connectionString="data source=Dell-PC\SQLEXPRESS;initial catalog=PromoteMyName;integrated security=True;" providerName="System.Data.SqlClient" />

Point 2 : I think you have done some trouble with inbuilt Membership Db Sure Short Solution for you problem is go to your db remove the Aspnet / Inbuilt tables ( i mean to drop the tables in db that are created by code first membership )

After removing those tables . Now Clean the Solution and Then ReBuild the solution , Then Run the Solution It will automatically create the new memebership tables in the database .

The entity type ApplicationUser is not part of the model for the current context, DB First with custom user store

Much to my chagrin, I had to go with option 2 above. I changed my connection string to be like a regular connection string (see above) and then had to consequently override a number of UserManager methods that I wasn't dealing with before (such as manager.GetRolesAsync() and manager.CreateIdentityAsync). I'm now able to register, reset passwords, etc.

Solution - The entity type ApplicationUser is not part of the model for the current context

You may get this error for a variety of reasons. This is not a guaranteed fix but hopefully it will save some time for someone out there. This error shows up usually because your application is using a default DbContext and not the one you're intending to use.

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DefaultConnection") {}
}

The project generates this custom DbContext. You should make sure the "DefaultConnection" is either the connection string or the name of the connection in your Web.config of your project using this class.

This is my connection string. Note that the name is the same as the one in the DbContext above:

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-AspnetIdentitySample-10_8_3;Integrated Security=True" providerName="System.Data.SqlClient" />

Once you made sure your connection string is set up, we need to check the bindings in NinjectWebCommon.

kernel.Bind<ApplicationDbContext>().ToSelf();
kernel.Bind<IUserStore<ApplicationUser>>().To<UserStore<ApplicationUser>>().WithConstructorArgument("context", kernel.Get<ApplicationDbContext>());
kernel.Bind<UserManager<ApplicationUser>>().ToSelf();

This is where I found the error in my application. The first line is not required but is a good idea. The second line is the most important.

UserStore has 2 constructors. The first is empty. The second has 1 parameter, DbContext context. Ninject's constructor arguments are case-sensitive and must be named "context" for Ninject to properly select this constructor.

The entity type ApplicationUser is not part of the model for the current context. Updated EDMX

Assumed this is your EF EDMX connection string:

<add name="FakeExistingDBConnectionString" connectionString="xxxxxxxxxxxxxxx;user id=fake_user;password=fakeUser12;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

The connection string above most likely triggering the problem, since generated connection string uses EntityClient instead of SqlClient provider which required by EF to communicate with data source. Note that you need to include standard SQL Server connection string targeting the DB where ASP .NET Identity tables created.

Hence, correct setup for your DB connection string should be like this:

<connectionStrings>
<add name="FakeExistingDBConnectionString" connectionString="xxxxxxxxxxxxxxx;user id=fake_user;password=fakeUser12;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Another connection string for EDMX:

<connectionStrings>       
<add name="FakeExistingDBConnectionEntities" connectionString="metadata=res://*/Models.ModelName.csdl|res://*/Models.ModelName.ssdl|res://*/Models.ModelName.msl;provider=System.Data.SqlClient;provider connection string="xxxxxxxxxxxxxxx;user id=fake_user;password=fakeUser12;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>

Additionally, the connection string referenced in ApplicationDbContext should refer to SqlClient provider connection string:

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

Then, update the EDMX and ensure you can manage users (create, login, update, password reset etc.)

Similar issue:

ASP.NET/Identity Error: The entity type ApplicationUser is not part of the model for the current context

The entity type ApplicationUser is not part of the model for the current context, DB First with custom user store



Related Topics



Leave a reply



Submit