Matteo Sganzetta
Matteo Sganzetta

Reputation: 788

Adding an attribute to an IdentityUser default property

I'm using ASP.NET Identity 2.2.1 in an MVC 5 solution and I extended the default IdentityUser entity with some custom properties.

Now I was wondering whether there's a way to add some attributes to the existing default properties. Specifically I'd like to add a [Display] attribute to PhoneNumber and UserName properties. I know I should map my model entity to a viewmodel one and have the display attribute on it, but sometimes I'm lazy :)

Thanks

Upvotes: 1

Views: 1164

Answers (1)

tmg
tmg

Reputation: 20383

You can add a metadata class to IdentityUser entity

[MetadataType(typeof(UserMetaData))]
public class User : IdentityUser<int, UserLogin,UserRole, UserClaim>, IEntity
{        
     public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User, int> manager)
     {
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            return userIdentity;
     }
}

public class UserMetaData
{
     [Display(Name = "PhoneNumber")]
     public virtual string PhoneNumber { get; set; } 
}

NOTE: I agree with the comments above that you should not to use your Entitiy Models in views and use ViewModels.

Upvotes: 1

Related Questions