roy adam
roy adam

Reputation: 3

Identity Entity Framework in IdentityDbContext change all Identity class to custom class

my old context is like

public class MYDbContext : IdentityDbContext<IdentityUser, IdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim> 
{
}

but I need some custom property in these classes changed them to

public class MYDbContext : IdentityDbContext<CustomUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim> 
{
}
public class CustomUser : IdentityUser
{       
    public virtual Person Person { get; set; }
}

public class CustomRole : IdentityRole
{
    public int Type { get; set; }
}

public class AppUserRole : IdentityUserRole
{
    public int Type { get; set; }
}

and also CustomUserLogin, CustomUserClaim are the same as others without any extra property.

The problem is when i try to add new role or user I get this exception:

System.Data.Entity.Validation.DbEntityValidationException: 'Validation failed for one or more entities. See 'EntityValidationErrors'

How can I fix it?

I tried to change my key type to Guid and it does not work, and also I tried to change only UserRole class to IdentityUserRole, but then I got a new error CS0311 :

Cannot be used as type parameter 'TUser' in the generic type or method 'IdentityDbContext<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim>'. There is no implicit reference conversion

Upvotes: 0

Views: 113

Answers (1)

MR Alam
MR Alam

Reputation: 141

i think error CS0311 you faced because you didn't define your user-role class to others i mean like :

public class CustomUser : IdentityUser<string, YourCustomUserLogin, YourCustomUserRole, YourCustomUserClaim>
{       
}

public class AppUserRole : <string, YourCustomUserRole>
{
}

and when you do it the Error " There is no implicit reference conversion " should vanish. and in my case when I define it as i said, you inherited class (IdentityRole) changed to a generic one look these two pictures: or in this link look Microsoft class IdentityRole IdentityRole generic IdentityRole generates Id inside Constructors. that isn't Constructors for the generic one (IdentityRole) So one of your solutions is ,create Constructors to generate Id like :

 //
        // Summary:
        //     Constructor
        public IdentityRole()
        {
            base.Id = Guid.NewGuid().ToString();
        }

        //
        // Summary:
        //     Constructor
        //
        // Parameters:
        //   roleName:
        public IdentityRole(string roleName)
            : this()
        {
            base.Name = roleName;
        }

or in some way generate your CustomClass ID

Upvotes: 0

Related Questions