Reputation: 197
I am trying to add custom fields for my IdentityUser. I have been through the documentation and also several articles that I've found online. I was able to figure out how to add custom fields, but I'm not sure how to set constraints on them. None of the articles I've found have covered this topic.
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public DateTime RegistrationDate { get; set; }
public string IPAddress { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
My code example is above. I have added 2 fields. RegistrationDate and IPAddress. I've used PowerShell to create the migrations and update the database.
My questions are this:
I am able to go into the migration files and make some changes after creating the migration, but those changes are not reflected in the database. If I try to re-run Update-database from PowerShell, I get an error saying that there are no changes to update.
On top of that. I don't know if I should be manually updating the migration files, since they are generated code.
public partial class IPAddress : DbMigration
{
public override void Up()
{
AddColumn("dbo.AspNetUsers", "IPAddress", c => c.String(nullable: false, maxLength: 39));
}
public override void Down()
{
DropColumn("dbo.AspNetUsers", "IPAddress");
}
}
I'm using Visual Studio 2015 and version 4.6.
Thanks
Upvotes: 2
Views: 4734
Reputation: 35106
1) To have a default date on your RegistrationDate
you need to create a default constructor of ApplicationUser
that sets your date to be whatever you need:
public ApplicationUser()
{
RegistrationDate = DateTime.Now();
}
2) To change the size of the field you need to apply [MaxLength(39)]
attribute on your IPAddress
field:
[MaxLength(39)]
public string IPAddress { get; set; }
3) To get BINARY
you need to use byte[]
type in C#. (ref: https://stackoverflow.com/a/1158670/809357)
4) You should not change the scripts for migrations manually - migrations contain XML snapshot of the database and keeps that snapshot in the __MigrationsHistory
table. So if you change the migration script, the snapshot will not be re-generated and EF won't pick up your changes.
When you change your data model you either create a new migration via add-migration NewMigrationName
or rollback your DB to a previous migration state via update-database -Target PreviousMigrationName
and then re-generate existing migration via add-migration ExistingMigrationName -Force
and then do Update-database
Upvotes: 3