@@ -19,22 +19,28 @@ public AuthorRepository()
19
19
20
20
public Author RetrieveById ( int authorId )
21
21
{
22
- //var result = _connection.Query<Author>("select * from author where id=@id", new {Id = authorId}).SingleOrDefault();
23
22
var authors = new Dictionary < long , Author > ( ) ;
24
23
25
24
var result = _connection . Query < Author , Article , Author > (
26
- "select * from author join article on article.authorid=author.id where author.id=@Id" ,
25
+ "select * from author left join article on article.authorid=author.id where author.id=@Id" ,
27
26
( author , article ) => {
28
27
if ( ! authors . ContainsKey ( author . Id ) )
29
28
{
30
29
authors [ author . Id ] = author ;
31
- author . Articles = new List < Article > ( ) ;
30
+ if ( article != null )
31
+ {
32
+ author . Articles = new List < Article > ( ) ;
33
+ }
32
34
}
33
35
else
34
36
{
35
37
author = authors [ author . Id ] ;
36
38
}
37
- author . Articles . Add ( article ) ; return author ;
39
+ if ( article != null )
40
+ {
41
+ author . Articles . Add ( article ) ;
42
+ }
43
+ return author ;
38
44
} ,
39
45
new { Id = authorId } ) ;
40
46
@@ -55,8 +61,37 @@ public Author RetrieveById(int authorId)
55
61
56
62
public List < Author > FetchAll ( )
57
63
{
58
- var authors = _connection . Query < Author > ( "select * from author order by name" ) . ToList ( ) ;
59
- return authors ;
64
+ //var authors = _connection.Query<Author>("select * from author order by name").ToList();
65
+
66
+ var authors = new Dictionary < long , Author > ( ) ;
67
+
68
+ var result = _connection . Query < Author , Article , Author > (
69
+ "select * from author left join article on article.authorid=author.id order by author.name" ,
70
+ ( author , article ) => {
71
+ if ( ! authors . ContainsKey ( author . Id ) )
72
+ {
73
+ authors [ author . Id ] = author ;
74
+ if ( article != null )
75
+ {
76
+ author . Articles = new List < Article > ( ) ;
77
+ }
78
+ }
79
+ else
80
+ {
81
+ author = authors [ author . Id ] ;
82
+ }
83
+ if ( article != null )
84
+ {
85
+ author . Articles . Add ( article ) ;
86
+ }
87
+ return author ;
88
+ } ) ;
89
+
90
+ if ( authors . Count > 0 )
91
+ {
92
+ return authors . Values . ToList ( ) ;
93
+ }
94
+ return null ;
60
95
}
61
96
62
97
public bool Save ( Author author )
0 commit comments