2016-11-21 3 views
0

PostComments을 나타내는 엔티티가 2 개 있습니다. Entity Framework 속성으로 하위 엔터티를 가져옵니다.

public class Post 
{ 
    public int Id { get; set; } 
    public ICollection<Comment> Comments { get; set; } 

    //other properties 


    //Unmapped property 
    public int NumberOfComments { get; set; } 

} 

public class Comment 
{ 
    public int Id { get; set; } 
    public Post Post { get; set; } 
    public int PostId { get; set; } 

    // other properties 
} 

는 지금은 NumberOfComments 속성이 게시물의 코멘트 실제 계수로 채워 싶다.
  • 는 모델은 운동을하지 않았다 게시물의 컬렉션에서 쿼리의 결과를 투영하는 시도.

  • 테이블에 가입하려고 시도했지만 아직 ID가 그룹화되어 있지 않은 경우 이 작동하는 것 같습니다.

내가 할 수 단순히 return p.Comments.Count; 내가 쿼리시 주석을 포함하고 있지 않다으로 속성 정의로. 나는 단지 메모리에있는 모든 콜렉션이 아니라 주석의 수를 원한다.

+3

'공공 INT NumberOfComments을 {얻을 {Comments.Count를 반환(); }}'? –

+0

나는 코멘트를 포함하고 있지 않다. 나는 단지 의견 수를 얻고 싶다. – Aneef

+0

'select new Post {Id = p.Id, NumberOfComments = p.Comments.Count()}'쿼리에서 명시 적으로 요청해야한다고 생각합니다. – juharr

답변

0

.Count()을 사용하여 의견 수를 얻을 수 있습니다. 이 라인에 대해

public class Post 
{ 
    public int Id { get; set; } 
    public ICollection<Comment> Comments { get; set; } 

    //other properties 

    //Unmapped property: Since it's value depends on the Comments collection 
    //we don't need to define the setter. If the collection is null, it'll 
    //return zero. 
    public int NumberOfComments 
    { 
     get 
     { 
      return this.Comments?.Count() ?? 0; 
     } 
    } 
} 

... 우리가이 널 (null) 연산자를 사용하고 return this.Comments?.Count() ?? 0; 여기

의 :

public class Post 
{ 
    public int Id{ get; set; } 
    public ICollection<Comment> Comments { get; set; } 

    //other properties 

    //Unmapped property 
    public int NumberOfComments { get { return Comments.Count(); } } 

} 
+0

댓글을 달았습니다. 나는 단지 의견 수를 얻고 싶다. – Aneef

+0

당신이 코멘트를 포함하지 않는다는 것은 무엇을 의미합니까? 그들은 다음과 같습니다 : public ICollection Comments {get; 세트; } - 그것은 당신의 코드가 아닌가요? – agfc

+2

@AlexeiFimine EF에서 탐색 속성으로 표시되는 모든 관련 테이블에 대해 항상 모든 데이터를 가져 오는 것은 아닙니다. – juharr

0

당신은 항상 당신이 다음과 같은 일을 할 수있는 댓글 탐색을 검색 Suposing Null 조건부 연산자 ? 및 Null 통합 연산자 ??. this.Comments?.Count() 되돌아가 NULL 인 경우, 왼쪽 식 널 되돌 오른쪽 발현하므로 때

처음 하나 주석 재산권 즉시 null 값을 반환하여 널인 경우 .Count()를 호출하기 전에 오류를 발생하는 코드를 피하고, 두 번째 동작

+0

아래 내 대답을 참조하십시오. 항상 0이 될 것입니다. bcoz 저는 항상 코멘트를 검색하지는 않습니다. – Aneef

+0

Matts 응답에 대한 제 응답과 juharrs 응답을 참조하십시오. 나는에 대해 알고 있어요 ?? 연산자 및 탐색 속성 하지만 위의 내용과 혼동하는 경우 – Aneef

+0

각 글마다 주석을 검색하지 않으면 다른 쿼리에서 개별적으로 계산할 수 있습니다 (설정자를 NumberOfComments 속성에 반환해야 함). myPost.NumberOfComments = .db.Comments.Where (c => c.PostId == postId) .Count(); –

0

이것이 내가 찾은 방법입니다.

다음 클래스가 필요하다 :

public class PostExtraData 
{ 
    public Post post { get; set; } 
    public int NumberOfComments { get; set; } 
} 

public class Post 
{ 
    public int Id { get; set; } 
    public ICollection<Comment> Comments { get; set; } 

    //other properties 

} 

public class Comment 
{ 
    public int Id { get; set; } 
    public Post Post { get; set; } 
    public int PostId { get; set; } 

    // other properties 
} 

컨텍스트에 PostExtraData 클래스를 추가하지 마십시오.

그리고 컨트롤러에 우리는 다음 (게시물이 경우, 얻을 수있는 목록) 작성 :

return _context.Post 
     .Select(p => new PostExtraData 
     { 
      Post= p, 
      NumberOfComments = p.Comments.Count(), 
     }) 
     .ToList(); 
관련 문제