Промежуточное сопоставление Dapper

Чуть более продвинутое сопоставление, чем в моем предыдущем вопросе:)

Таблицы:

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)
)

Классы:

public class Primary
{
    public int Id { get; set; }
    public Customer Customer { get; set; }
    public DateTime Date { get; set; }
    public List Secondaries { get; set; }
}

public class Secondary
{
    public int Id { get; set; }
    public DateTime Date { get; set; }
    public List 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; }
}

Можно ли использовать один выбор, чтобы заполнить их все? Что-то вроде этого:

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
";

А затем:

IEnumerable primaries = connection.Query(
    sqlStatement,
   ... here comes dragons...
    );

Edit1 -Я мог бы сделать это с помощью двух вложенных циклов (foreach secondaries -> foreach tertiaries)и выполнить запрос для каждого элемента, но просто интересно, может быть выполнено с помощью одного вызова базы данных.

Edit2 -возможно, здесь подойдет метод QueryMultiple, но, если я правильно понимаю, мне потребуется несколько операторов select. В моем примере из реальной жизни выбор имеет более 20 условий (в предложении where ), где параметр поиска может быть нулевым, поэтому я не хотел бы повторять все те операторы where во всех запросах...

9
задан Community 23 May 2017 в 01:59
поделиться