3

I am actually trying to override the IdentityRole class coming with asp.net.identity to enable 'multi-tenancy' role.

I already overrided the class as follow :

public class ApplicationRole : IdentityRole, IIdentifiableEntity<string>, ITenantable
{
    public Tenant Tenant { get; set; }
    public Guid TenantId { get; set; }
    public string Description { get; set; }

    public ApplicationRole() : base() { }
    public ApplicationRole(string name) : base(name) { }
    public ApplicationRole(string name, Guid tenantId) : base(name)
    {
        this.TenantId = tenantId;
    }

    public string EntityId
    {
        get { return Id; }
        set { Id = value; }
    }
}

This is working fine. Now i need to change the primaryKey to have a composedKey so i can have 'admin' with tenantId = 1 and 'admin' with tenantId = 2.(note that i am using fluent api).

I tried two things... first:

public ApplicationRoleMap()
    {
        // Primary Key
        HasKey(t => t.Id);

        Property(t => t.Name).HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_RoleTenant", 1) { IsUnique = true }));
        Property(t => t.TenantId).HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_RoleTenant", 2) { IsUnique = true }));

        HasRequired(t => t.Tenant).WithMany().WillCascadeOnDelete(false);
        Ignore(t => t.EntityId);
    }

this one added the unique constraint but kept the unique primary key on name so i cannot create two role with the same name but with different tenantId.

Then i tried :

public ApplicationRoleMap()
    {
        // Primary Key
        HasKey(t => new { t.Id, t.TenantId });

        //Property(t => t.Name).HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_RoleTenant", 1) { IsUnique = true }));
        //Property(t => t.TenantId).HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_RoleTenant", 2) { IsUnique = true }));

        HasRequired(t => t.Tenant).WithMany().WillCascadeOnDelete(false);
        Ignore(t => t.EntityId);
    }

This should work, but when running update-database, it says there is no pending change as if my primary key attribut were not taking in charge. I guess the TKey set on IRole.Id is taken instead...

How can i achieve it?

Doum
  • 397
  • 3
  • 14

0 Answers0