2014-10-21 3 views
1

이것은 정말 저에게 다가 오기 시작했습니다. 기본 사항으로, 사용자가 UserProfile 테이블에 이미있는 이메일로 등록하는 것을 방지하고 싶습니다. 왜 ASP.NET MVC4의 사용자 등록 작업에서 중복 된 전자 메일 주소의 유효성을 검사 할 수 없습니까?

는 내가있는 나는이 모델이 생성되는 동안 컨텍스트를 사용할 수없는 오류 - 수

private UsersContext db = new UsersContext(); 

    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserEmail.Equals(useremail)); 
     if(user != null) 
     { 
      ModelState.AddModelError("UserEmail", "User email already exists. Please enter a  different email."); 
     } 

사용하여 계정 컨트롤러 - 내 등록 액션에 다음을 시도했다. OnModelCreating 메서드 내에서 컨텍스트가 사용되거나 동일한 컨텍스트 인스턴스에 여러 스레드가 동시에 액세스하는 경우이 예외가 throw 될 수 있습니다. 나는 또한 (UserName 속성 근무) 원격 속성

[AllowAnonymous] 
    [HttpPost] 
    public JsonResult doesEmailExist(string UserEmail) 
    { 
     return Json(!db.UserProfiles.Any(user => user.UserEmail == UserEmail), JsonRequestBehavior.AllowGet); 
    } 

을 시도 - 그것을 가진 속성을 장식

DbContext와 관련 클래스의 인스턴스 멤버를 참고 스레드 안전이 보장되지 않습니다

[Remote("doesEmailExist", "Account", HttpMethod = "POST", ErrorMessage = "Email address already exists. Please enter a different Email address.")] 

에러 - (내부 예외) { "열 이름이 유효하지 않다. 노드 이름 (있는 경우) = Extent1 컬럼 이름 = USEREMAIL]"}

어디서 잘못 되었습니까? POST 양식에서 일어나는 경우에도 간단한 검사 만 찾고 있습니다. 참고 사항 - 면도기 뷰 및 simpleMembership을 사용하는 mvc 4 응용 프로그램입니다. 감사합니다. AccountModel

  public DbSet<UserProfile> UserProfiles { get; set; } 
} 

[Table("UserProfile")] 
public class UserProfile 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int UserId { get; set; } 
    public string UserName { get; set; } 
    public string UserEmail { get; set; } 
} 
+0

'UserEmail'은'UserProfiles'에 존재하지 않습니다. –

+0

편집을 참조하십시오. – mkell

+0

첫 번째 시도가 정확합니다. 문제가 모델 생성에서 오류가 있는지 확인합니다. 엔티티 프레임 워크 코드를 먼저 가정합니다. –

답변

0

에서

사용자 프로필 필드 UserEmail에 고유 키를 추가합니다. 당신의 Register 행동

alter table UserProfile add constraint UK_UserEmail Unique(UserEmail); 

:

try 
{ 
    WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { UserEmail = model.UserEmail}); 
    WebSecurity.Login(model.UserName, model.Password); 
    return RedirectToAction("Index", "Home"); 
} 
catch (MembershipCreateUserException e) 
{ 
    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); 
} 
catch (SqlException e) 
{ 
    if (e.Message.Contains("UK_UserEmail")) 
    { 
     ModelState.AddModelError("Error","Email cannot be duplicate"); 
    } 
} 

이가 최선의 방법으로 간주 될 수 있다면 모르겠지만, 헤이, 그것은를 작동합니다!

+0

VS 서버 탐색기 또는 SQL을 통해 테이블을 변경하면 문제가 발생합니까? – mkell

+0

@mkell 아니오, 어디에서나 할 수 있습니다. –

+0

전설! 그것은 멋지게 할 것입니다. 고맙습니다. – mkell