,entity-framework-6, , Understanding Identity key points

Understanding Identity key points



I am an developer but very much new to the Identity framework. I have been studying the sample application and followed some tutorials too on Identity but still I am not able to grasp the concept completely. I have very firm grip over membership but Identity seems nothing like membership. I will explain what I have done so far.

I am creating a simple application in which I am following code first approach. I have created entity model for User which inherits from IdentityUser and has some extra fields. Below is entity model for User.

public class User : IdentityUser
    public int? CompanyID { get; set; }

    public bool? CanWork { get; set; }

    public bool? CanSearch { get; set; }

    public Company Company { get; set; }

Now in the examples people use the name ApplicationUser but for my own purpose I have used name User. Also there is a method in User or ApplicationUser model which is,

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;

I am unable to understand the purpose of this method. Also from an example I have used the following model for Role,

public class Role : IdentityRole
    public Role()


    public Role(string roleName, string description)
        : base(roleName)
        this.Description = description;

    public string Description { get; set; }

I understand that an extra field is added but I am unable to understand the purpose of overloaded constructor.

The above mentioned confusions are secondary. My primary confusion is that I am familiar that when I create entity models I use DbSet and DbContext and when I call any entity framework method to access the database, the database is created/drop created whichever scheme I am following.

In Identity which method is responsible for creating the Identity tables in the database? I have a IdentityConfig file in which I declare ApplicationUserManager and ApplicationSignInManager. I have also a Startup file. Previously I had only one Startup file in the App_Start folder and when I run the application and tried to accessed any Identity methods it gave me error and was not creating database. I then made the class as partial and created another partial class with same name at the root and then the exception was gone and tables were created. So Startup class is responsible for creating Identity tables? There are extra columns created automatically in the AspNetUsers like PhoneNumber, PhoneNumberConfirmed, TwoFactorEnabled. I don't need these extra columns. Can I remove these? Can I change the names of the Identity tables that are created?

I know these are very basic questions and not one question at all but if I was unable to find some basic tutorial or example for beginners then it would be very beneficial. What I have found are describing those things which I don't need or making me confuse. I want to understand and have control how Identity should work in my application but till now it seems to me that neither I am grasping it completely and nor being able to make is adjustable to my needs. Its like tutorials and example are teaching me how to make sentences but I am unable to understand the alphabets. :(


First of all you have to define the model - as you're doing - implementing the right interfaces.
Let's say you want to create a user for your application:

public class MyUser : IdentityUser<string, MyUserLogin, MyUserRole, MyUserClaim>
    public string CompanyName { get; set; }

As you can see I've implemented the IdentityUser interface (namespace Microsoft.AspNet.Identity.EntityFramework).

I've specified what type of identifier I want to use for my primary key (string) and included my custom objects to manges login, roles and claims.

Now we can defined the role object:

public class MyRole : IdentityRole<string, MyUserRole>

Again there's a type and the class I've defined for the management of users belonging to to a role.

public class MyUserRole : IdentityUserRole<string>

MyUserLogin is going to implement IdentityUserLogin<string>.
MyUserClaim is going to implement IdentityUserClaim<string>.

As you can see each interface need a type for the primary key.

The second step is to create the user store:

public class MyUserStore:  UserStore<MyUser, MyRole, string, MyUserLogin, MyUserRole, MyUserClaim>
    public MyUserStore(MyContext context)
        : base(context)

Again we have defined what user, role, login etc etc we want to use.
We need UserStore cause our UserManager is going to need one.

If you're planning to manage roles and associate roles with each user you have to create your RoleStore definition.

public class MyRoleStore : RoleStore<MyRole, string, MyUserRole>
    public DaufRoleStore(ApplicationDatabaseContext context) : base(context)

Now you can create your UserManager. The UserManager is the real responsible of saving changes to the UserStore.

public class ApplicationUserManager : UserManager<MyUser, string>
    public ApplicationUserManager(IUserStore<MyUser, string> store)
        : base(store)


    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
        var manager = new ApplicationUserManager(new MyUserStore(context.Get<MyContext>()));

        manager.UserValidator = new UserValidator<MyUser, string>(manager)
        AllowOnlyAlphanumericUserNames = false,
        RequireUniqueEmail = true

        manager.PasswordValidator = new PasswordValidator()
        RequiredLength = 5,
        RequireNonLetterOrDigit = false,     // true
        // RequireDigit = true,
        RequireLowercase = false,
        RequireUppercase = false,

        return (manager);

This class has a static method which will create a new UserManager for you.
Interesting to note that you can include some validation rules you might need to validate password etc etc.

Last thing is to create or database context.

public class MyContext : IdentityDbContext<MyUser, MyRole, string, MyUserLogin, MyUserRole, MyUserClaim>
    public MyContext(): base("<your connection string here>")


    public static MyContext Create()
        return new MyContext();

    protected override void OnModelCreating(DbModelBuilder modelBuilder)






As you can see I've used the model builder to change the names all the tables. You can define keys or fields type or tables relations here.

This is the place where you're going to attach your custom classes you want to manage in your context:

public DbSet<MyCustomer> Customers{ get; set; }

Again MyContext has a Create method which returns a new context:

public static MyContext Create()
    return new MyContext();

Now you should have a startup class where you're going to bootstrap your stuff:

[assembly: OwinStartup(typeof(ASPNETIdentity2.Startup))]

namespace ASPNETIdentity2
    public class Startup
        public void Configuration(IAppBuilder app)

Here you're going to create your database context and your user manager you can use in your application.

Notice the first line:

[assembly: OwinStartup(typeof(ASPNETIdentity2.Startup))]

This is needed cause you're telling your environment that is the startup class which needs to be called at ... startup.

Now in your controllers you can simply refer to your UserManager doing something like this:


How can you create your tables?

In Visual Studio go to TOOLS -> NuGet Packager Manager -> Package Manager Console.

In the window there's a combobox "Default Project". Choose your ASP.NET MVC project.
Run this command:


It will create a file Configuration.cs in a new folder called Migrations.
If you want to create your database you need to open that file and change the AutomaticMigrationsEnabled to true:

public Configuration()
    AutomaticMigrationsEnabled = true;

Again, from Package Manager Console, you can run:


and all your tables will appear in your database. Don't forget your connection string.

You can download this github project to see how everything works.
You can check these two answers with some other info.

The first of the two has got some links to a blog where you can learn all these things.


You have to do all this if you want to customized every single bit of your environment.


Embedding a Silverlight App into a MVC

I decided to convert the WPFs into a Silverlight applications. My only problem is trying to get it to display the silverlight application in my MVC web browser. I added all of my silverlight projects into my MVC project. I am just not getting it to show my silverlight application....

Future plans to consider for mvc 5.2 web application, with releasing mvc6 (vnext),,,,
I need to get any ideas of how i should be managing our previous MVC 5.2 web application.. now i am using mvc-5.2 with entity framework 6.0. and i want to start phase-2 for some of these projects. so should i consider upgrading my mvc 5.2 to be...

How to append Urls in angular routing?,angularjs,,angularjs-ng-repeat,angular-ui-router
How to do url(string) cocatenation in angular routing. Please refer the below snippet to understand my question. app.config(['$routeProvider', '$location'], function($routeProvider) { when('/', { templateUrl: '/AlbumsList.html', controller: 'a1Ctrl' }). when('/albums/:albumName', { templateUrl: 'AlbumsList.html', controller: 'b1Ctrl' }) }) app.controller('a1Ctrl', function($scope, $http) { $scope.albums = function() { //ajax getting data from server }...

MvcSiteMapProvider - Enhanced bootstrap dropdown menu

I'm trying to build a menu like this: For reference I'm using this library @Html.MvcSiteMap().Menu("BootstrapMenuHelperModel") @model MenuHelperModel <nav class="navbar" role="navigation"> <div class="container-fluid menu-container"> <div class="collapse navbar-collapse"> <div class="navbar-header"> <span class="navbar-brand">FAR BACKOFFICE</span> </div> <ul class="nav nav-pills"> @foreach (var node in Model.Nodes) { if...

How to augment actionlink with route values at runtime with JavaScript in ASP.NET MVC 5?

I have this ActionLink. @Html.ActionLink("Link", "action", "controller", null, htmlAttributes: new {@class = "menuLink"}) I have to set routeValues to null because I don't know the value at compiletime. They are recieved from the selectedvalue of some dropdowns at runtime. Hence, I am trying to augment the routevalues at runtime with...

Unable to cast code first

Having this class that represents model public class User : IHaveId { public User() { Operations = new Collection<Operation>(); } public int Id { get; set; } public string UserName { get; set; } public string CardNumber { get; set; } public string Pin { get; set; } public double...

Need to fetch Oracle RAW in C# string datatype “as is”

Help me out, requirement is that I need the same value of Oracle RAW to be in C# as a string. I am able to save String as RAW value in oracle table, but while fetching it is giving exception "Object must implement IConvertible" which I can understand that since...

How to get tables from database first approach without .tt and edmx files?

I am working on database first approach. I followed the following link I'm able to get the cs files. But cs file are coming under edmx folder. but I want to get cs file directly as similar as code first approach I am using entity framework 6 and mvc...

Web API AuthorizeAttribute does not return custom response

How can I make IsAuthorized return my custom object while function returns false? In my WebAPI project I have a class like; public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) { StandardWebAPIResponse invalidUserResponse = new StandardWebAPIResponse() { code = (int) Constants.ErrorCodes.InvalidCredentials, data = "InvalidCredentials.", StatusCode = HttpStatusCode.Unauthorized...

How to use ajax to post json string to controller method?

I want to be able to post a json string to a control action but it's always receive the string as null. If I create a view model for the controller method, it works, but that's not what I want since there will be too much view models to maintain....

Convert SQL to linq statement

I would like to convert the SQL syntax below to a linq statement to get a single boolean result back. The SQL is checking if a user exists in a current role. select case when exists (select 1 from Global.Application as a join Global.Role as r on a.ID = r.ApplicationId...

EF Code first - many to many relation mapping table with extra columns

I am having a User Model and and a Group Model. User and Group share a many to many relationship. In when I translate this to table, I want to have a mapping table. I am using the following to achieve this. modelBuilder.Entity<UserGroup>() .HasMany(a => a.Users) .WithMany(b => b.UserGroup) .Map(mc...

Linq Conditional DefaultIfEmpty query filter

I have a query as below: bool variable = false//or true var query = from e in _repository.GetAll<Entity>() from u in e.Users where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId from p in e.PractitionerProfiles.DefaultIfEmpty() select new { entity = e, user = u, profile = p }; This...

Entity Framework Code First - Optional/required two-way navigation

I have a code first model similar to the following: public class TestContext : DbContext { public DbSet<Class1> Class1s { get; set; } public DbSet<Class2> Class2s { get; set; } } public class Class1 { public int Class1Id { get; set; } } public class Class2 { public int Class2Id...

How to get routevalues from URL with htmlhelpers or JavaScript?

I have this MVC MapRoute routes.MapRoute( name: "Authenticated", url: "{controller}/{action}/{foo}/{bar}", defaults: new { controller = "Home", action = "WelcomePage", Foo = "0", Bar = "0" } ); And URL http://localhost/mysite/controller/action/2/1 How can I with JavaScript recieve the 2 and 1? I would prefer a solution with as little substring work...

EPPlus: how can I assign border around each cell after I apply LoadFromCollection?

In my export ActionResult I was able to load the model into my ExcelPackage. Where I am having trouble is assigning a border around each cell once LoadFromCollection is applied. While the AutoFitColumns correctly applies, the border style I applied only works on Cells["D1"], but not on the table. BorderAround...

Asp.Net MVC 5 + Bootstrap. How make inputs fit screen width?

I really don't know what I'm doing wrong. I want my textboxes with same size of my buttons below. I already tried change a lot in the cshtml but without success. Below my cshtml file: @model SomeModel.Models.LoginViewModel <div class="row"> <div class="col-md-8 col-sm-12 col-xs-12"> <section id="loginForm"> @using (Html.BeginForm("Login", "Account", new {...

MVC: after export to excel, index action result is not getting called,export-to-excel
I have one MVC application, in which export to excel functionality is given. I want to redirect Index action once export is finished. I have written below code but it not redirected to index action. what i missed here ? output = new MemoryStream(); workbook.Write(output); Response.ContentType = "application/"; Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",...

Error while connecting to database in code-first Entity Framework

I am getting following error message when context is trying to connect to database using code-first approach of Entity Framework System.Data.Entity.DbContext' does not contain a definition for 'System' and no extension method 'System' accepting a first argument of type 'System.Data.Entity.DbContext' could be found (are you missing a using directive or...

IronPython entity framwork 6 Could not find attribute where

I have successfully integrated entity framework into my project. I'm also able to read data from a table over my dbcontext. But when i try to use the linq where method, i get the following error message: 'DbSet[Workflow]' object has no attribute 'Where' This is my code: import clr import...

Store does not implement IUserLockoutStore,
I'm trying to implement own DAL for Identity 2.0 with functionality that I need. I don't need Account Lockout functionality. But When I try to call var result = await SignInManager.PasswordSignInAsync(model.Login, model.Password, model.RememberMe, shouldLockout: false); I get System.NotSupportedException:Store does not implement IUserLockoutStore<TUser>. So why should I need to implement...

Distribute entity framework models over different assemblies

Currently i am trying to use entity framework 6.3 with a kind of distributed models. My problem is, i want to seperate the models in different assemblies (for example the core application and plugins). Now i'm search for a way, that my application get all models over reflection or some...

Why is KnockoutJS not showing the same number of objects as my Web API controller?

The solution was the same as in this question: How to get an observableArray's length? ...but the question itself is unique so anyone in the same situation will hopefully have an easier time finding the answer than I did. I'm fairly new to Knockout and to Web API. I've built...

Produce different serialized JSON for a given class in different scenarios

Update 1: for reasons I won't go into, I want to avoid having anything other than the properties to be persisted in my entity objects. This means no extra properties or methods... I have an entity called Entity1 with (say) 10 public properties. In one place in my code I...

Am I required to put multiple Entity Framework Models in their own projects in the same solution?

I am using Entity Framework 6 in a Windows Form application. The problem is that I have to connect to 4 different databases with almost identical tables. Each year we rollover the databases and allow users in the current year to load 3 previous years of data for some of...

In MVC Razor, how can I correctly add querystring parameters to an html.actionlink?,razor,
I have an MVC Razor page where I am trying to add a querystring parameter to the URL. <td> @Html.ActionLink(item.Student_Name, "Index", "FourCourseAuditDetails", new { filterByStudent = item.Student_Name}) </td> My desired outcome is: http://[server]/FourCourseAuditDetails/Index?filterByStudent="[item.Student_Name]", but when I test out the page, the anchor href attirubte looks like this: http://[server]/[route of current...

How do I properly send __RequestVerificationToken with an ajax request in MVC5

I'm trying to send an ASP.NET AJAX request to my application. In the application's controller, I have: [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "ID,Name,Instructions,Glass,Notes")] Drink drink, [Bind(Include= "ID,Amount,Brand,IngredientID,DrinkID")] IEnumerable<DrinkIngredient> DrinkIngredients) { if (ModelState.IsValid) { //and so on my javascript looks like this: console.log($('#editDrinkForm').serialize()) var x = new XMLHttpRequest(); x...

Best approach to upgrade MVC3 web app to MVC5?

I have a web application which runs on Azure which is currently running MVC3/C#, EF6.1, .NET4.5. I would like to upgrade it to MVC5 to be: a) Current b) Get benefit of new features c) Get Performance gains. This is a part of a performance project, so hopefully there will...

Convert string value to english word

I'm trying to figure out / where to start in regards to this situation say for example I enter $127.45 in to a textbox I would expect the application to spit back one hundred and twenty-seven dollars and forty-five cents The word will then be placed on a document and...

MVC route attribute no controller,,
I'm building an intranet where I have the following home controller: [Route("{action=index}")] public class HomeController : Controller { public ActionResult Index() { return View(HomeModelBuilder.BuildHomeModel()); } public ActionResult FormsHome() { return View(HomeModelBuilder.BuildFormsHomeModel()); } } I'm trying to get my forms homepage to have a url of http://intranet/forms so I thought I...

How detailed should your repository be? Testing issues [closed]

In my controller, I have something like this: class HomeController { [AllowAnonymous] public ActionResult Index() { HomeViewModel viewModel = new HomeViewModel(); viewModel.FieldSearchCriteria = new SearchCriteria(); viewModel.Blogs = this.unitOfWork.BlogRepository.GetAllPublishedBlogs(1, 2, "PublishDate", SortDirection.DESC, null).ToList(); viewModel.FieldWanteds = this.unitOfWork.FieldWantedRepository.GetAllFieldWanteds( 1, 2, "CreatedAt", SortDirection.DESC, null ).ToList(); viewModel.Fields =...

MVC 5 - Validate a specific field on client-side

I want to populate a city/state drop down list based on the postal code a user types into a textbox. So when the text changes, I'm going to make an ajax call to retrieve the data. However, I only want to perform that ajax request for valid postal codes. The...

string.Format is not giving correct output when INR currency symbol (Rs.) come to display

While display bank transaction data to INR currency symbol (Rs.), output is not coming correct way. I need to display currency symbol along with 2 decimal points with thousand separator. I have tried so far1: column.PropertiesEdit.DisplayFormatString = string.Format("{0} #,0.00", Model.CurrencySymbol); I have used DevExpress MVC GridView. Current output when INR...

Property Is Required on Update EF6

I have a property that is required on my entity. Upon adding the entity to the database, that property is populated by the system. From here on, this property should never be changed. This property is also never passed to the client. So now when the user edits this entity,...

MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?,,razor,,claims-based-identity
I'm trying to learn Claims for MVC 5 OWIN login. I try'ed to keep it as simple as possible. I started with the MVC template and inserted my claims code (see below). I get an error when I use the @Html.AntiForgeryToken() helper in the View. Error: A claim of type...

Knockout js unable to bind data using observableArray

I am trying to display all the employees in the database and I am unable to achieve it. My JS, var EmployeeKoViewModel = function () { var self = this; self.EmpId = ko.observable(""); self.Name = ko.observable(""); self.City = ko.observable(""); self.Employees = ko.observableArray([]); GetEmployees(); function GetEmployees() { $.ajax({ type: "GET", url:...

Catch concurrency exception in EF6 to change message to be more user friendly

I am using EF6.1 and i would like to change the message to a more system specific message when the below exception is thrown. Store update, insert, or delete statement affected an unexpected number of rows (0) Now, my problem is i cannot seem to catch the exception? I have...

How to upgrade mvc2 to mvc5?,,
I've got an old project from a friend that he wants me to do redo. How ever that project is written in mvc2. So When I try to open it in visual studio 2013 I can errors. Saying the file is incompatible. How would I go ahead and fix...

Entity Framework connection factory not working

I use entity framework 6 and try to overwrite the connection string factory. I've written the following connection factory: internal class MyDBConnectionFactory : IDbConnectionFactory { public System.Data.Common.DbConnection CreateConnection(string nameOrConnectionString) { SAConnection connection = new SAConnection(ConnectionManager.GetConnectionString(nameOrConnectionString ?? "Default")); return connection; } } Than i have written my own configuration class: public...

Web API Basic Auth inside an MVC app with Identity Auth

So I have a C# MVC app using Identity for its authentication. I now have a need to expose a few things via Web API to some of my clients. Instead of building a separate app, project, deployment... I've simply added an API Controller to my existing project. To keep...

ApplicationUser ICollection member not being saved in DB

I've added some properties to ApplicationUser, and two of them are ICollection's. When I use Update-Database it doesn't generate columns for these two members. So, what am I missing here? I imagine it's very basic. I'm used to working with Hibernate in Java, where it generates a new table for...

Entity Framework Automatic migration

I have a 3-tier architecture project (Web, Service, DataAccess), I just want to migrate the database to latest version whenever POCO changes happen. We can do this by calling the automatic migration code from Application_Start event. In this scenario, I don't have the reference of the DataAccess project in my...

Inherited Property of Model is always returning Null Value

I have a view which displays a radiobutton list on left side of the page and it also loads a partialview on right side of the page which consist of various filters to be selected before displaying a report in a popup window. The problem is that the property named...

Database object with different data

I'm making a web page in ASP.NET MVC which compares prices from different shops. I have a one-to-many with products and the shops, where the SHOP has one PRODUCT and a PRODUCT has many SHOPs, the problem is that the product is the same but the price is different. Example:...

LINQ: Searching inside child entities

I have 'Property' objects with 'BayOption' child objects. I need the site search to search through the child BayOptions as well as the Properties and return Properties if the search criteria matches the child or parent. A Property can have multiple BayOptions (and usually does). I was unsure if .Select...

Converting string to datetime in mapping to viewmodel

I have an MVC app where I collect DateTime fields (MM/dd/yyyy) as strings to avoid Chrome overriding the datepicker in bootstrap and to avoid mapping in sqlbulk upload of Excel. I now need to map this string field back to datetime and am struggling with this greatly. Here's my Model:...

EPPlus export model to Excel: System.NullReferenceException

I have an MVC view that correctly displays a model. Now that I have been asked to put an Export to Excel function on that page, I heard about EPPlus and gave it a try. From this site I thought I had something that would simply do the job. After...

Getting users from another AD Domain using PrincipalContext

How would I get users from an AD Group which contains users from different domains. For example, I have 2 domains in my active directory, and I have an AD group called TestGroup which contains users from both the domains. Domain1 users: TestUser1, TestUser2 Domain2 users: TestUser3, TestUser4,...

MVC/Razor: Error at Viewbag.Title

I have two methods: public ActionResult Index() { var propList = db.Properties .Where(x => x.SiteVisibilityFlags.HasFlag(Enums.SiteVisibilityFlags.Corporate) || (x.SiteVisibilityFlagsOverride == true && x.SiteVisibilityFlagsOverrideValue.HasFlag(Enums.SiteVisibilityFlags.Corporate))) // just ones visible to 'Corporate' .ToList(); // Use view model var pDVMs = DomainModelsToViewModels(propList); return View(pDVMs); } public ActionResult Region(string id) // (regionId/marketId) { // make sure to...

DbSet.Attach(entity) vs DbContext.Entry(entity).State = EntityState.Modified

When I am in a detached scenario and get a dto from the client which I map into an entity to save it I do this: context.Entry(entity).State = EntityState.Modified; context.SaveChanges(); For what is then the DbSet.Attach(entity) or why should I use the .Attach method when EntityState.Modified already attaches the entity?...