Ich versuche es herauszufinden, aber ich kann es nicht zur Arbeit bringen. Diese Abfrage:
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
Dies wird diese Daten zurückgeben:
Wie Sie sehen, stammen die Zeilen 1 und 2 aus demselben Titel. Die Daten dahinter sind Bücher. Zeile 3 und 4 sind ebenfalls Sammlungen, haben aber keine Bücher.
Ich habe zwei Objekte in meinem Code: MultiCollection Collection
Beide entsprechen den im Ergebnis der Abfrage angegebenen Daten: Id, UserId und Title sind für das Objekt MultiCollection. Andere Daten sind für das Objekt Sammlung.
Ich erwarte drei MultiCollections in meinem C # -Code: Action Drama Fiction
Aktion wird 2 Sammlungen haben. Drama und Fiktion sollte leer sein.
Stattdessen erhalte ich 4 MultiCollections und keine von ihnen enthält Sammlungen. Mein C # -Code:
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;
});
}
}
Wenn ich den Code ausführe, würde ich folgendes erwarten:
Action
Collections
-> Book 1
-> Book 2
Drama
Collections
Null
Fiction
Collections
Null
Ich habe keine Ahnung, was ich falsch mache.
Ihr c # -Code sollte folgendermaßen aussehen:
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"););
}
}
Beachten Sie, dass .Query<MultiCollection, Collection, MultiCollection>
eine Collection
nicht List<Collection>
und es tut .add()
und nicht Setter.