leggermente più avanzato poi nei miei previous question :)Dapper mappatura intermedia mappatura
Tabelle:
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)
)
Classi:
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; }
}
E 'possibile utilizzare una select per riempire tutti? Qualcosa di simile a questo:
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
";
E poi:
IEnumerable<Primary> primaries = connection.Query<Primary, Customer, Secondary, Tertiary, Primary>(
sqlStatement,
... here comes dragons ...
);
Edit1 - ho potuto farlo con due cicli annidati (secondari foreach -> foreach terziari) ed eseguire una query per ogni articolo, ma chiedo solo se potesse essere fatto con una singola chiamata al database.
Modifica2 - forse il metodo QueryMultiple sarebbe appropriato qui, ma se ho capito bene avrei bisogno di più istruzioni select. Nel mio esempio di vita reale la selezione ha più di 20 condizioni (nella clausola where), dove il parametro di ricerca potrebbe essere nullo quindi non vorrei ripetere tutti quelli in cui le affermazioni in tutte le query ...