Dapper Intermediate Mapping

Etwas fortgeschritteneres Mapping als in meinemvorherige Frage :)

Tabellen:

<code>create table [Primary] (
    Id int not null,
    CustomerId int not null,
    CustomerName varchar(60) not null,
    Date datetime default getdate(),
    constraint PK_Primary primary key (Id)
)

create table Secondary(
    PrimaryId int not null,
    Id int not null,
    Date datetime default getdate(),
    constraint PK_Secondary primary key (PrimaryId, Id),
    constraint FK_Secondary_Primary foreign key (PrimaryId) references [Primary] (Id)
)

create table Tertiary(
    PrimaryId int not null,
    SecondaryId int not null,
    Id int not null,
    Date datetime default getdate(),
    constraint PK_Tertiary primary key (PrimaryId, SecondaryId, Id),
    constraint FK_Tertiary_Secondary foreign key (PrimaryId, SecondaryId) references Secondary (PrimaryId, Id)
)
</code>

Klassen:

<code>public class Primary
{
    public int Id { get; set; }
    public Customer Customer { get; set; }
    public DateTime Date { get; set; }
    public List<Secondary> Secondaries { get; set; }
}

public class Secondary
{
    public int Id { get; set; }
    public DateTime Date { get; set; }
    public List<Tertiary> Tertiarys { get; set; }
}

public class Tertiary
{
    public int Id { get; set; }
    public DateTime Date { get; set; }
}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>

Ist es möglich, mit einer Auswahl alle zu füllen? Etwas wie das:

<code>const string sqlStatement = @"
    select 
        p.Id, p.CustomerId, p.CustomerName, p.Date,
        s.Id, s.Date,
        t.Id, t.Date
    from 
        [Primary] p left join Secondary s on (p.Id = s.PrimaryId)
        left join Tertiary t on (s.PrimaryId = t.PrimaryId and s.Id = t.SecondaryId)
    order by 
        p.Id, s.Id, t.Id
";
</code>

Und dann:

<code>IEnumerable<Primary> primaries = connection.Query<Primary, Customer, Secondary, Tertiary, Primary>(
    sqlStatement,
    ... here comes dragons ...
    );
</code>

Edit1 - Ich könnte es mit zwei verschachtelten Schleifen machen (foreach secondaries -> foreach tertiaries) und für jedes Element eine Abfrage durchführen, aber ich frage mich nur, ob dies mit einem einzelnen Datenbankaufruf möglich ist.

Edit2 - Vielleicht wäre die QueryMultiple-Methode hier angebracht, aber wenn ich das richtig verstehe, würde ich mehrere select-Anweisungen benötigen. In meinem realen Beispiel hat das select mehr als 20 Bedingungen (in der where-Klausel), wobei der Suchparameter null sein könnte, sodass ich nicht alle where-Anweisungen in allen Abfragen wiederholen möchte ...

Antworten auf die Frage(3)

Ihre Antwort auf die Frage