Entity Framework 6, MVC5, ASP Identity 2.0.
I have followed this 2 tutorials to create the login part of the web application: part 1 - part 2
I created my own AppUser class from IdentityUser Class in another library project. I also have my data context from the IdentityDbContext
public class DataContext: IdentityDbContext<AppUser>
{
public DataContext(): base("DefaultConnection") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<AppUser>().Property(u => u.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
base.OnModelCreating(modelBuilder);
}
}
public class AppUser : IdentityUser
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public override string Id { get; set; }
[Required]
[Display(Name ="First Name")]
[MaxLength(100)]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
[MaxLength(100)]
public string LastName { get; set; }
[MaxLength(100)]
public string Title { get; set; }
[Required(ErrorMessage = "Email is required.")]
[Display(Description = "Email")]
public override string Email { get; set; }
[MaxLength(20)]
public string Phone { get; set; }
[Range(0,9999)]
[Display(Name = "Extension")]
public int PhoneExtension { get; set; }
[Display(Name = "Active")]
[DefaultValue(true)]
public bool IsActive { get; set; }
}
When I run the seed method I get the following error
System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Id', table 'CRM1.dbo.AspNetUsers'; column does not allow nulls. INSERT fails. The statement has been terminated.
Here is the seeding method:
protected override void Seed(CRM.DAL.Data.DataContext context)
{
context.AccessLevels.AddOrUpdate(al => al.Label,
new Model.AccessLevel { AccessLevelID = 1, Label = "Admin", Description = "Full access to the CRM data" },
new Model.AccessLevel { AccessLevelID = 2, Label = "Customer Service", Description = "Full access to the CRM data" },
new Model.AccessLevel { AccessLevelID = 3, Label = "Sales", Description = "Full access to the CRM data" }
);
if (!(context.Users.Any(u => u.UserName == "admin@admin.com")))
{
var userStore = new UserStore<AppUser>(context);
var userManager = new UserManager<AppUser>(userStore);
var userToInsert = new AppUser
{
Id = "1",
FirstName = "Admin",
LastName = "Admin",
Title = "Administrator",
Email = "admin@admin.com",
PhoneExtension = 0,
IsActive = true,
AccessLevelID = 1,
EmailConfirmed = true,
PhoneNumberConfirmed = true,
TwoFactorEnabled = false,
LockoutEnabled = false,
AccessFailedCount = 0,
UserName = "admin"
};
userManager.Create(userToInsert, "password");
}
}
So Id gets a value but EF says it is inserting NULL. I tried by not giving any value to Id thinking EF would do it automatically but no.
What is the approach to seed an AspNetUser with my context? I saw different tutorials but it does not apply to my extended AppUser class and DataContext.
Thank you