Skip to content

Commit 99dfc3c

Browse files
committed
Great, that's many-to-many done at least with a single many list eg; author -> articles. Next is Article -> tags. Going for a run now.
1 parent ff5f721 commit 99dfc3c

File tree

1 file changed

+41
-6
lines changed

1 file changed

+41
-6
lines changed

Dapper-a-simple-web-app/Repositories/AuthorRepository.cs

Lines changed: 41 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,22 +19,28 @@ public AuthorRepository()
1919

2020
public Author RetrieveById(int authorId)
2121
{
22-
//var result = _connection.Query<Author>("select * from author where id=@id", new {Id = authorId}).SingleOrDefault();
2322
var authors = new Dictionary<long, Author>();
2423

2524
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",
2726
(author, article) => {
2827
if(!authors.ContainsKey(author.Id))
2928
{
3029
authors[author.Id] = author;
31-
author.Articles = new List<Article>();
30+
if(article != null)
31+
{
32+
author.Articles = new List<Article>();
33+
}
3234
}
3335
else
3436
{
3537
author = authors[author.Id];
3638
}
37-
author.Articles.Add(article); return author;
39+
if(article != null)
40+
{
41+
author.Articles.Add(article);
42+
}
43+
return author;
3844
},
3945
new {Id = authorId});
4046

@@ -55,8 +61,37 @@ public Author RetrieveById(int authorId)
5561

5662
public List<Author> FetchAll()
5763
{
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;
6095
}
6196

6297
public bool Save(Author author)

0 commit comments

Comments
 (0)