AspNet Identity 2.0 Email and UserName duplication
My current Asp.Net MVC 5 project mandates Email address for UserName. Now I want to upgrade ASPNet Identity v1.0 to v2.0 to leverage all its new features (see here).
However, ASPNet Identity v2.0 adds Email as a separate column to the Users table and adds a corresponding property to the IdentityUser class.
I don't want to duplicate UserName into this new Email column. How can I map this Email Property of IdentityUser to use existing UserName column & property? Is it possible to ignore this Email property and skip adding the column in the Users table? Has anybody tried this?
Please share.
Update
This is the identity 2.0 limitation. We cannot ignore Email property or leave it Null. Some of the Identity functionality will not work. :(
You can try one of these:
Try to ignore it by either overriding Email
property in your User
class and unmapping it or using fluent API.
public class ApplicationUser : IdentityUser
{
// ....
[NotMapped]
public override string Email { get; set; }
}
or
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ApplicationUser>().Ignore(u => u.Email);
}
When you register your user just make sure that you populate Email
with your UserName
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
// ...
}
}
Of course, you can always ignore Email
column if you're not going to use it, since it allows NULLs, it'll just be sitting in your AspNetUsers
table with bunch of NULLs, not the best approach but remember that by ignoring it you might lose new features that ASP.NET Identity 2 might offer that you might want to use.
NOTE However I'm not sure if option number 1 will work on Email
property since it's probably used all over the place in new Identity code. Worth a try though. I know that's how you can get rid of other columns if you don't need them. I personally happen to use new Email
property/column so I haven't tried it.
Not sure if it helps you, but thought I'd share it just in case.
I have the same problem, and the way that I resolved it was that the email address was the same as the username when creating a user:
var newUser = new ApplicationUser()
{
UserName = email,
Email = email,
};
However, if you try to create an account with a duplicate username, you will get 2 validation errors, one for the username field, and one for the email address.
To get around that, allow email addresses to not be unique (they will still be unique though as your usernames are unique) by editing the identityconfig.cs file:
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = false
};
链接地址: http://www.djcxy.com/p/78574.html
上一篇: CSS - 取消最后一个字母的额外空间