I'm trying to extend the ApplicationUser class so that I can contain UserProfile
information in a separate table. However I'm having trouble getting this to work and am getting
an exception when I call the UserManager.CreateAsync
method in my AccountController.
Invalid column name 'UserProfileId'.
My Application User class
public class ApplicationUser : IdentityUser
{
[ForeignKey("UserProfileId")]
public virtual UserProfile UserProfile { get; set; }
public int UserProfileId { get; set; }
}
My User Profile class
public class UserProfile
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required, MaxLength(200)]
public string EmailAddress { get; set; }
[Required, MaxLength(50)]
public string FirstName { get; set; }
[Required, MaxLength(50)]
public string LastName { get; set; }
}
My first entity generated code migration
CreateTable(
"dbo.AspNetUsers",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
UserName = c.String(),
PasswordHash = c.String(),
SecurityStamp = c.String(),
UserProfileId = c.Int(),
Discriminator = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.UserProfile", t => t.UserProfileId, cascadeDelete: true)
.Index(t => t.UserProfileId);
My code to create the new user on Registration
var user = Mapper.Map<ApplicationUser>(model);
var result = await UserManager.CreateAsync(user, model.Password);
With Automapping config of
Mapper.CreateMap<RegisterViewModel, ApplicationUser>()
.ForMember(dest => dest.UserProfile, opt => opt.MapFrom(v => Mapper.Map<RegisterViewModel, Data.Model.UserProfile>(v)));
Mapper.CreateMap<RegisterViewModel, Data.Model.UserProfile>()
.ForMember(dest => dest.FirstName, opt => opt.MapFrom(v => v.FirstName))
.ForMember(dest => dest.LastName, opt => opt.MapFrom(v => v.LastName))
.ForMember(dest => dest.EmailAddress, opt => opt.MapFrom(v => v.EmailAddress));
NOTE: I have tried removing the int UserProfileId
and this instead created a field called UserProfile_Id
which caused issues in and of itself.