2017-10-16 1 views
0

이것을 이해하려고 시도했지만 작동하지 않습니다. 이 쿼리 :이이 데이터를 반환합니다Dapper로 일대일 매핑

select MultiCollections.*, Collections.* from MultiCollections 
left join MultiCollectionCollections on MultiCollections.Id = MultiCollectionCollections.MultiCollectionId 
left join Collections on MultiCollectionCollections.CollectionId = Collections.Id 
where MultiCollections.UserId=5 

:

enter image description here 당신이 볼 수 있듯이, 행 1과 2는 동일한 제목에서입니다. 그 뒤에있는 데이터는 책입니다. 행 3과 4는 모음이지만 책이 없습니다.

두 쿼리의 결과에 주어진 데이터에 해당 MultiCollection 컬렉션 : 아이디, 사용자 ID와 제목 개체 MultiCollection위한

나는 내 코드에서 두 개체가 있습니다. 다른 데이터는 Collection 개체입니다. 이 명 컬렉션을해야합니다 액션 드라마 소설

작업 :

나는 내 C# 코드에서 세 MultiCollections를 볼 것으로 예상. 드라마와 픽션은 비어 있어야합니다.

대신 4 개의 MultiCollection이 있고 그 중 누구도 모음을 포함하지 않습니다. 내 C# 코드 :

public IEnumerable<MultiCollection> GetAll(int userId) 
    { 
     string query = @"select MC.*, C.* from MultiCollections MC 
         left join MultiCollectionCollections MCC on MC.Id = MCC.MultiCollectionId 
         left join Collections C on MCC.CollectionId = C.Id 
         where UserId=" + userId; 

     using (DbConnection connection = ConnectionFactory()) 
     { 
      connection.Open(); 
      return connection.Query<MultiCollection, List<Collection>, MultiCollection>(query, 
       (a, s) => 
       { 
        a.Collections = s; 
        return a; 
       }); 
     } 
    } 

내가이 기대할 수있는 코드를 실행 :

Action  
    Collections  
     -> Book 1  
     -> Book 2  
Drama  
    Collections  
     Null  
Fiction  
    Collections  
     Null 

나는 내가 잘못 뭘하는지 모르겠어요.

+0

어떤 유형이'a.Collections'입니까? 'List '입니까? – 12seconds

+0

넵, 목록

답변

0

귀하의 C# 코드는 다음과 같이의해야합니다

public IEnumerable<MultiCollection> GetAll(int userId) 
{ 
    string query = @"select MC.*, C.* from MultiCollections MC 
        left join MultiCollectionCollections MCC on MC.Id = MCC.MultiCollectionId 
        left join Collections C on MCC.CollectionId = C.Id 
        where UserId=" + userId; 

    using (DbConnection connection = ConnectionFactory()) 
    { 
     connection.Open(); 
     return connection.Query<MultiCollection, Collection, MultiCollection>(query, 
      (a, s) => 
      { 
       a.Collections = new List<Collection>(); 
       a.Collections.Add(s); 
       return a; 
      }, splitOn: "MultiCollectionId,CollectionId");); 
    } 
} 

공지 사항, .Query<MultiCollection, Collection, MultiCollection>Collection하지 List<Collection>이며이 .add()하지 세터을하고있다.

+0

이제 3 대신 4 개의 MultiCollections가 생깁니다. 첫 번째 2 개는 각 해당 책과 동일합니다. 그러나 두 책은 하나의 다중 수집 아래에 추가되어야합니다. –

+0

Ps. a.Collections.add (s)는 a이어야합니다 .Collections.Add (s) (capital) 및 a.Collections는 처음 실행시 null이므로 초기화해야합니다 ... 그냥 힘들지는 말하지 마십시오. –

+0

@KenjiElzerman, yah, np. IDE없이 입력하고 있습니다. 내 머리 꼭대기에. – 12seconds