2012-04-03 3 views
2

이 웹 사이트에서 사용자는 사용자 이름과 암호로 등록 할 수 있으며 아티클에 의견을 게시 할 수도 있습니다. 모델은 매우 간단하다 : 데이터베이스가 코드를 먼저 사용하여 만들 때Entity Framework가 테이블에 새 레코드를 만듭니다. 다른 테이블에 삽입 할 때 참조하지 않았 음

public class User 
{ 
    public int Id { get; set; } 
    public string Username { get; set; } 
    public string Password { get; set; } 
    public bool IsAdmin { get; set; } 
    public DateTime JoinDate { get; set; } 
    public string AvatarPath { get; set; } 
    public string EmailAddress { get; set; } 
} 

public class ArticleComment 
{ 
    public int Id { get; set; } 
    public int ArticleId { get; set; } 
    public int UserId { get; set; } 
    public string CommenterName { get; set; } 
    public string Message { get; set; } 
    public DateTime CommentDate { get; set; } 
    public User User { get; set; } 
} 

엔티티 프레임 워크가 제대로 사용자에 ArticleComment 및 ID를 사용자 아이디와 외래 키 관계를했다.

다음은 사용자가 게시물 새로운 코멘트를 할 때 내 코드의 다음 newComment를 구성

public JsonResult SubmitComment(int articleId, string comment) 
    { 
     var response = new JsonResponse(); 
     var currentUser = _userRepository.GetUserByUsername(User.Identity.Name); 

     //... 

     var newComment = new ArticleComment 
     { 
      ArticleId = articleId, 
      CommentDate = DateTime.Now, 
      CommenterName = currentUser.Username, 
      UserId = currentUser.Id, 
      User = currentUser, 
      Message = comment, 
     }; 

     try 
     { 
      _articleRepository.Insert(newComment); 
     } 
     catch (Exception e) 
     { 
      response.Success = false; 
      response.AddError("newComment", "Sorry, we could not add your comment. Server error: " + e.Message); 
      return Json(response); 
     } 

     response.Success = true; 
     response.Value = newComment; 
     return Json(response); 
    } 

값은 모두가 올바른 것으로 보인다 객체, 나의 제 저장소 클래스의 삽입 방법은 똑바로하는 것입니다 포인트 : 내 사용자의 새로운 기록이 표 ArticleComments에서 새로운 기록과 함께 나타납니다

public void Insert(ArticleComment input) 
    { 
     DataContext.ArticleComments.Add(input); 
     DataContext.SaveChanges(); 
    } 

그러나 이것은, 휙 발생하면

. 새 사용자 레코드의 모든 정보는 해당 사용자의 기존 레코드에서 복제됩니다. 유일한 차이점은 기본 키 ID의 값입니다. 뭐라 구요?

+0

ArticleComment에 사용자 탐색 속성이 가상 할 필요가 :'공공 가상 사용자 사용자 {얻을; 세트; }' – danludwig

+0

만약 내가 추측한다면, 그것은'User = currentUser,'줄과 관련이있을 것이다. 컨텍스트가 무엇을 생각하는지 보려면 EntityState 개체를 확인하십시오. –

답변

3

내 의견 외에도 _userRepository_articleRepository이 동일한 DbContext 인스턴스를 사용하고 있는지 확인해야합니다.

어느 쪽이든을, 또는 당신이 시도 할 수 있습니다 :

var newComment = new ArticleComment 
{ 
    ArticleId = articleId, 
    CommentDate = DateTime.Now, 
    CommenterName = currentUser.Username, 
    UserId = currentUser.Id, 
    // User = currentUser, let the UserId figure out the User, don't set it yourself. 
    Message = comment, 
}; 
+0

고맙습니다. 왜 그 속성을 처음부터 설정하려했는지 확신 할 수 없습니다 ... – AJH

관련 문제