For starter, i would like to say thanks to JOBG for intracting with me through this. What i showed in the question above should still work if you use Database First
as it demands that you set Email column UNIQUE
in the database, however to make it work with EF Code First
i had to do the following to the register action, also note that with this solution, you don't need Remote Annotation in the model
:
Register Action
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Insert a new user into the database
using (UsersContext db = new UsersContext())
{
UserProfile email = db.UserProfiles.FirstOrDefault(u => u.Email.ToLower() == model.Email.ToLower());
try
{
// Check if email already exists
if (email == null)
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email });
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("Email", "Email address already exists. Please enter a different email address.");
}
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Note: Take note that this action validates Email before UserName and that it requires that you take a trip to the database atleast once before you create your object.