I am writing an application using the VS2013 SPA template that includes Asp.NET Identity, WebAPI2, KnockoutJS and SqlServer Express 2012.
I started off using the IdentityUser class to handle my users and that worked just fine. I was able to add and login as a user with no problem. I then wanted to add custom information to the IdentityUser (there was an article I can no longer find).
As a result, I created an User class that inherited from IdentityUser as seen below.
public class User : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Then I updated all the references in the project from IdentityUser to User.
Now, whenever I try to login I get the following error:
The entity type User is not part of the model for the current context.
The thing is, I have a DBInitializer (public class ApplicationDBInitializer : DropCreateDatabaseAlways<ApplicationDBContext>) that always recreates the database and adds some test users and the tables are created and the users are added successfully.
On the off chance it matters, here is my cxn string: <add name="DefaultConnection" connectionString="Server=.\SQLEXPRESS;Database=ibcf;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
and my DBContext
public class ApplicationDBContext : IdentityDbContext<User>
{
public ApplicationDBContext()
: base("DefaultConnection")
{
}
}
Why is this error happening?
The issue was that the Startup.Auth.cs continued to reference the default IdentityDbContext<User> DB context. After updating the class to reference my ApplicationDBContext the issue was resolved.
static Startup()
{
...
UserManagerFactory = () => new UserManager<User>(new UserStore<User>(new ApplicationDBContext()));
...
}
Related
I'm trying to connect to the local database instance that visual studios provides, I setup a connection string in the appsettings.json however, it keeps failing at the integrated security keyword, it says it doesn't exist. However if I take it out, the response gets a timeout because there was no pre-authorization handshake which is because I set my dbcontext to identitydbcontext so I would need to specify the integrated security = true keyword but alas I'm stuck
This is the default connection string:
"DefaultConnection":"Server=(localdb)\\\\
mssqllocaldb;Database=ChatAppTr;MultipleActiveResultSets=true;
Integrated Security=True;"
This is how I setup the database context for my web app:
///Specify what type of user you want in identity context:
public class AppDbContext : IdentityDbContext<User>
{
public AppDbContext(DbContextOptions<AppDbContext> options) :
base( options){ }
/// Registers models to AppdbContext
public DbSet<Chat> Chats { get; set; }
public DbSet<Messages> Messages { get; set; }
}
}
I expected it to just connect to the localdb instance but nothing happened.
In ASP.NET MVC 5, in a controller, I have take the user that has make the request with:
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
With the ApplicationUser instance, how can i get all the Roles of the user?
You can get user and assigned roles by using UserManager.
var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
and then you can get your user like you already did, and also you can get roles for particular user by calling GetRoles method
userManager.GetRoles(userId);
List<string> roles = new UserManager().GetRoles(userIdString)).ToList();
below needed classes were created automatically in ASP.NET 4.5 project using VS 2015 using . the file name is IdentityModels.cs.
default 4 Nuget packages are installed including Microsoft.AspNet.WebApi v5.2.3
public class UserManager : UserManager<ApplicationUser>
{
public UserManager()
: base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
{
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
public class ApplicationUser : IdentityUser
{
}
I am starting a vNext project, and I'm having some issues kicking it off the ground. I have added a table to the ApplicationDbContext class, and it successfully created the table in the db (which in my case is in Azure). However, I can't seem to correctly instantiate a dbContext to use in my Controllers.
In my experience with previous ASP.NET EF projects, I could instantiate the ApplicationDbContext class without passing it any parameters, but in the case of vNext however, it seems to expect a number of things (IServiceProvider, and IOptionsAccessor<DbContextOptions>). I have tried creating a parameter-less constructor, but the App breaks due to not knowing what connection strings to use. My code is below -- as you see in the OnConfiguring(DbContextOptions options) override, I force the connection string in via the DbContextOptions, but that's obviously not ideal, and I feel like I'm just not understanding where those two IServiceProvider, and IOptionsAccessor parameters need to come from.
Thanks for any help!
namespace Project.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
public string CompanyName { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
private static bool _created = false;
public DbSet<Business> Businesses { get; set; }
public ApplicationDbContext()
: base()
{
if (!_created)
{
Database.EnsureCreated();
_created = true;
}
}
protected override void OnConfiguring(DbContextOptions options)
{
var configuration = new Configuration();
configuration.AddJsonFile("config.json");
configuration.AddEnvironmentVariables();
options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString"));
}
public ApplicationDbContext(IServiceProvider serviceProvider, IOptionsAccessor<DbContextOptions> optionsAccessor)
: base(serviceProvider, optionsAccessor.Options)
{
// Create the database and schema if it doesn't exist
// This is a temporary workaround to create database until Entity Framework database migrations
// are supported in ASP.NET vNext
if (!_created)
{
Database.EnsureCreated();
_created = true;
}
}
}
}
IServiveProvider and IOptionAccessor are injected by the Dependency Injection
the ASP.Net Core DI has limitation, you cannot have more than one constructor.
Read this: http://blogs.msdn.com/b/webdev/archive/2014/06/17/dependency-injection-in-asp-net-vnext.aspx
I see the same issue as this question, but the scenario presented there doesn't seem to apply so I think I have a different issue. In fact, I'm seeing several questions on SO that are similar, each with different causes and solutions, so I think this error must be caused from a high level. That said...
I have an EF code-first database model and I'm trying to use IdentityUser to extend a standard registration for my MVC 5 site.
I have my extended UserModel:
namespace MyMvcSite.Models
{
public class UserModel : IdentityUser
{
public string BillingId { get; set; }
public virtual ICollection<DatabaseModel> Databases { get; set; }
}
}
And my context:
using MyMvcSite.Models;
namespace MyMvcSite.Web
{
public class AuthContext : IdentityDbContext<UserModel>
{
public AuthContext() : base("AuthContext") { }
}
}
Now, when I execute the code to register a user:
public async Task<IdentityResult> RegisterUser(UserModel user)
{
user.Email = user.UserName;
var result = await _userManager.CreateAsync(user);
return result;
}
I get this error:
The entity type IdentityUser is not part of the model for the current context.
I can't figure out what this error means, because it looks like I have everything correct. Can anyone tell what might be going wrong???
I know my connectionString AuthContext is correct because I have used it previously.
When you are using a custom user class with ASP.NET Identity, you have to make sure that you explicitly specify the custom user class type <T> to both the UserManager and the UserStore on instantiation.
private UserManager<UserModel> _userManager;
public AccountController()
{
AuthContext _ctx = new AuthContext();
UserStore<UserModel> userStore = new UserStore<UserModel>(_ctx);
_userManager = new UserManager<UserModel>(userStore);
}
or in shorter form (like your reply comment):
private UserManager<UserModel> _userManager;
public AccountController()
{
AuthContext _ctx = new AuthContext();
_userManager = new UserManager<UserModel>(new UserStore<UserModel>(_ctx));
}
If the type is allowed to defaulted to IdentityUser when you want to use a custom class you will experience the error you reported.
I was having this same problem, and I recall having a similar problem working with SimpleMembership in MVC4.
I’m doing database first development, so I have an EDMX file. Turns out, ASP.NET Identity does not like the connection string that is created when you generate your .edmx model file. If you are using a. EDM connection string in :base(“EDMConnString”) you will most likely have this problem.
I fixed this by creating a standard connection string that pointed to the database where the ASP.NET Identity tables are (in my case the same database), used that connection string in :base, and it worked.
Something like this
<add name="IdentityConnection" connectionString="data source=THEJUS\SQLSERVER2014;initial catalog=IdentitySample;integrated security=True;MultipleActiveResultSets=True;App=IdentitySample.Admin" providerName="System.Data.SqlClient" />
I got this error when I introduced DI to my project. Using AutoFac and Identity I had to add the following: builder.RegisterType<ApplicationDbContext>().As<DbContext>().InstancePerLifetimeScope();
Without this, when AutoFac was creating my UserStore instance, it was using the default UserStore() ctor which creates a new IdentityDbContext, not my ApplicationDbContext.
With this line, UserStore(DbContext context) ctor gets called, with my ApplicationDbContext.
Here is some step i figured out while resolving this issue
First Check your database for Table of ASP.Net Identity
Create these table on your database if not exist you can also apply migration
Check the below image and verify your code
Register Action
IdentityDbContext Class
I have Solution consisting of 3 projects, first is Data Access Layer (where models and Database Context are defined), and other two are Asp.net MVC 5 and Asp.net Web Api 2 projects.
For authentication and authorization I'm using Asp.net Identity which I've set up like this (in my DAL project):
public class DatabaseContext : IdentityDbContext<User>
{
public DatabaseContext()
: base("DefaultConnection")
{
Configuration.LazyLoadingEnabled = true;
}
public DbSet<IdentityUser> IdentityUsers { get; set; }
/*
Other DbSets ...
*/
}
My User class extends IdentityUser.
In my ASP.net project I've changed a bit Account controller so it works with my Database Context, here are relevant parts which I changed:
[Authorize]
public class AccountController : Controller
{
public AccountController()
: this(new UserManager<User>(new UserStore<User>(new DatabaseContext())))
{
}
public AccountController(UserManager<User> userManager)
{
UserManager = userManager;
}
public UserManager<User> UserManager { get; private set; }
}
And this part works fine. So my question is, what changes I have to do in order my Web API project works with my entity User and my Database Context, so in order to consume API user must be logged in ? (and of-course user has option to register via API).
I.E. I want to enable authorization and authentication for web api 2 by using my Database Context and class User which extends Identity User class.
UPDATE
What I've tried to do is this: I've replaced all IdentityUser classes in my web api 2 project with my class User, but on line (when I try to log in):
User user = await userManager.FindAsync(context.UserName, context.Password);
I get error:
System.Data.SqlClient.SqlException: Invalid object name 'dbo.AspNetUsers'.
This approach worked for my asp.net MVC project.
In short what I did was:
In my DatabaseContext class I've added these lines:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>()
.ToTable("AspNetUsers");
modelBuilder.Entity<User>()
.ToTable("AspNetUsers");
}
In asp.net web api project I've changed all classes IdentityUser to User, and that's it