2014-07-12 7 views
0

MVC 4에서 Upvote 함수를 주석으로 생성하려고하는데 이러한 upvote는 데이터베이스에 추가되지 않습니다. 나는 그 후 db.SaveChanges 문장이 실행되었고, 모든 것이 작동하는 것, 즉 upote가 있다는 것을 알고 나서 db.SingleOrDefault(x=> x.Id ==id)을 사용하여 주석을 다시 검색하려고 시도했다. 그러나 일단 컨트롤을 다시 요청하면 upvotes의 값은 null입니다.Object가 db.SaveChanges와 함께 저장되지 않았습니다. ASP.NET MVC 4

편집 : 나는이 문제를 해결했다. Entity Framework에서 기본 유형의 컬렉션을 만들 수 없으므로 기본 유형을 가진 새 클래스를 대신 만들어야합니다.

컨트롤러 :

public class AJAXController : Controller 
{ 
    // 
    // GET: /AJAX/ 

    private BlogDb db = new BlogDb(); 

    //[Authorize] 
    public ActionResult CommentUpvote(int id=0) 
    { 
     if (User.Identity.IsAuthenticated) 
     { 

      var comment = db.Commments.Find(id); 
      if (comment != null) 
      { 
       if (comment.UserNamesUpVoted == null) 
       { 
        comment.UserNamesUpVoted = new List<string>(); 
       } 

       if (comment.UserNamesUpVoted.Contains(User.Identity.Name)) 
       { 
        comment.UserNamesUpVoted.Remove(User.Identity.Name); 
        comment.Points--; 
        ViewBag.c = "down"; 
       } 
       else 
       { 
        comment.UserNamesUpVoted.Add(User.Identity.Name); 
        comment.Points++; 
        ViewBag.c = "up"; 
       } 

       db.Entry(comment).CurrentValues.SetValues(comment); 
       db.SaveChanges(); 

      } 
      else 
      { 
       ViewBag.c = "false2"; 
      } 
     } 
     else 
     { 
      ViewBag.c = "false1"; 
     } 


     return View(); 
    } 
} 

주석 클래스 :

public class Comments 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int Id { get; set; } // this must be an int. 

    public string Content { get; set; } 

    public DateTime Created { get; set; } 

    public int BelongsTo { get; set; } // null if does not belong, top comment. 

    //[ForeignKey("UserProfile")] 
    //public int UserId { get; set; } 
    //public virtual UserProfile UserProfile { get; set; } 

    public virtual ICollection<string> UserNamesUpVoted { get; set; } 

    public int Points { get; set; } 

    public virtual string UserName { get; set; } 

} 
+0

어떻게'public 가상 ICollection에 UserNamesUpVoted {얻을; 세트; }'는 데이터베이스에 저장됩니까? 나도 몰라,하지만 그 잘못된 엔터티 프레임 워크 엔터티 클래스를 생각합니다. 투표하려면 별도의 표가 있어야합니다. –

답변

0

나는 문제는 데이터로드와 있다고 생각합니다. Find 메서드를 사용하면 열심히로드가 수행되지 않고 관련 데이터가로드되지 않을 수 있습니다. Find은 당신이 찾고있는 개체를 반환하고 객체 캐시에없는 경우 자동으로 관련 기관을로드하지 않기 때문에 먼저 부하에 다음 제대로 UserNamesUpVoted을 수정 한 :

var comment = db.Commments.Find(id); 
context.Entry(comment).Reference(c => c.UserNamesUpVoted).Load(); 

또는

그 수정 코멘트 후
var comment = db.Commments.Include(c => c.UserNamesUpVoted).SingleOrDefault(c => c.Id == id); 

:

db.Entry(comment).CurrentValues.SetValues(comment); 
db.Entry(comment).State = EntityState.Modified; 
db.SaveChanges(); 
+0

이 작동하지 않는 것 같습니다. – Artem

+0

시도해 보셨습니까? –

+0

예. 첫 번째 예제에서는 오류가 발생합니다. 'Comments'유형의 'UserNamesUpVoted'속성은 탐색 속성이 아닙니다. Reference 및 Collection 메서드는 탐색 속성에서만 사용할 수 있습니다. Property 또는 ComplexProperty 메서드를 사용합니다. – Artem