Reputation: 2589
The AspNetRoles table has 2 columns "Id" and "Name". I need to add a third one: "Module(nvarchar(256), null)".
I found some articles on my search but the majority from years ago and a bit complex to me. I'm asking if there a simple way to do it using the EF?
Upvotes: 0
Views: 961
Reputation: 1
In my case, it wasn't as simple as creating a custom class. The generated migration was empty.
I had to also modify my DbContext class to inherit from this custom IdentityRole and then change many methods around to use new custom class because of the errors.
My custom DBContext definition:
CustomDbContext(DbContextOptions<KeyDbContext> options) : IdentityDbContext<SiteUser, SiteIdentityRole, string>(options)
Upvotes: 0
Reputation: 3651
Yes, there's a very simple way to do it.
Even though there's already an accepted answer, it doesn't show how to use it inside DbContext, that's why I decided to add mine.
Step 1: Create a custom role
public class ApplicationRole : IdentityRole
{
public string NewColumn { get; set; }
}
Step 2:
Use it in DbContext
// string in <ApplicationUser, ApplicationRole, string> is the Key type
public class ApplicationContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
For more info on customizing Identity model, take a look at this Microsoft Learn guide: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-7.0
ApplicationUser
looks like this:
public class ApplicationUser : IdentityUser
{
}
Step 3: Open Package Manager Console and use following command to create new migration:
PM> Add-Migration 'Add new column to roles table'
Step 4: Use following command to apply the migration into the database:
PM> Update-Database
Upvotes: 1
Reputation: 104
You could create a custom class that inherits from IdentityRole and add whatever properties you want in that class:
Create a custom class as shown below:
public class CustomIdentityRole : IdentityRole
{
public string NewColumn { get; set; }
}
Run EF migration command to generate the table model as shown below:
Add-Migration test2
public partial class test2 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "NewColumn",
table: "AspNetRoles",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "NewColumn",
table: "AspNetRoles");
}
}
Update-Database
Upvotes: 2