1

I have problem with Identity framework and custom role. My custom role contains a set of activity permission.

My custom role look like

public class MyRole : IdentityRole
{
    public List<MyPermission> Permissions { get; set; }
}

public class MyPermission
{
    public int Id { get; set; }
    public int Value { get; set; }
}

and RoleManager like this

public RoleManager<MyRole> MyRoleManager;

I can create new role but I have problem to update permission in role. I update like

myRole.Permissions.Clear();
myRole.Permissions.Add(new MyPermission() { ... });
MyRoleManager.Update(myRole);

new permission has been added but old permission still in database. How can I delete those olds.

Edited: I have more problem just noticed. When I use FindById from RoleManager, there is no permission load from database.

Thank you.

dokibi
  • 43
  • 8

1 Answers1

0

Assuming you are using Code First you will need to add the DbSet's to your Context:

DbSet<MyRole> Roles {get;set;}
DbSet<MyPermission> Permissions {get;set;}

You will also need to make sure that your collection is marked as a virtual ICollection:

public class MyRole : IdentityRole
{
    public virtual ICollection<MyPermission> Permissions { get; set; }
}
hutchonoid
  • 32,982
  • 15
  • 99
  • 104
  • Great solution!! It work well. MyPermission now automatically load and remove foreign key. However the MyPermission record still in database with null foreign key. Please guide me again how to delete those thing. thank you :) – dokibi May 20 '15 at 16:00
  • @dokibi No problem, please accept the answer if it worked. :) After you have removed you could just do a `SaveChanges()`. If you want `Permission` to be removed too you could set up a cascade delete as detailed here: http://stackoverflow.com/questions/17487577/entity-framework-ef-code-first-cascade-delete-for-one-to-zero-or-one-relations – hutchonoid May 20 '15 at 16:07
  • Thank you for your reply however it not work this time. After I added .HasOptional().WithOptionalDependent().WillCascadeOnDelete(true); and add-migration, EF generate sp_rename from not existing column and update-database show error Either the parameter@objname is ambiguous or the claimed @objtype (COLUMN) is wrong. – dokibi May 20 '15 at 17:13