Extending Asp.Net Identity 2.0 with custom fields

Recently I needed a quick and low friction way of extending Asp.Net Identity 2.0, tying into the Entity Framework 6 way of working with custom fields and table mappings. To accomplish this first create something similar to a new ContosoIdentityUser which inherits from IdentityUser.

ContosoIdentityUser.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using Microsoft.AspNet.Identity.EntityFramework;

namespace Contoso.Web
{
public class ContosoIdentityUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DOB { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string Suburb { get; set; }
public string State { get; set; }
public string Postcode { get; set; }
}
}

We then likewise create a new ContosoIdentityDbContext which inherits from IdentityDbContext.

ContosoIdentityDbContext.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

using Microsoft.AspNet.Identity.EntityFramework;

namespace Contoso.Web
{
public class ContosoIdentityDbContext : IdentityDbContext
{
public ContosoIdentityDbContext()
: base("DefaultConnection")
{

}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

if (modelBuilder == null)
{
throw new ArgumentNullException("modelBuilder");
}

SetIdentityUserModel(modelBuilder);
base.OnModelCreating(modelBuilder);
}

private void SetIdentityUserModel(DbModelBuilder modelBuilder)
{

modelBuilder.Entity().Property(x => x.FirstName).HasMaxLength(50).IsRequired();
modelBuilder.Entity().Property(x => x.LastName).HasMaxLength(50).IsRequired();
modelBuilder.Entity().Property(x => x.DOB).IsRequired();
modelBuilder.Entity().Property(x => x.AddressLine1).HasMaxLength(100).IsRequired();
modelBuilder.Entity().Property(x => x.AddressLine2).HasMaxLength(100).IsOptional();
modelBuilder.Entity().Property(x => x.Suburb).HasMaxLength(50).IsRequired();
modelBuilder.Entity().Property(x => x.State).HasMaxLength(3).IsRequired();
modelBuilder.Entity().Property(x => x.Postcode).HasMaxLength(4).IsRequired();
}
}
}

Now to stitch it all together in your boot strapper logic, in my case this is within Startup(), just wire up to our newly created extensions:

1
2
var userManager = new UserManager(new UserStore(new ContosoIdentityDbContext()));
UserManagerFactory = () => userManager;