Convert SQL to linq to SQL with cross apply -
this question has answer here:
any idea how convert cross apply sql query linq-to-sql?
select * dbo.company inner join dbo.contact c on c.contid = dbo.company.compcontactid or dbo.company.compcontactid null inner join dbo.company_program cp on cp.compid = dbo.company.compid or dbo.company.compid null inner join dbo.program p on cp.progid = p.progprogramid inner join dbo.division d on d.divid = p.progdivisionid inner join dbo.phonetype pt on pt.phtphonetypeid = c.contphonetypeid or c.contphonetypeid null inner join dbo.phonenumber ph on ph.phoneid = pt.phtphoneid or pt.phtphoneid null cross apply (select top 1* dbo.participation p p.participationid = dbo.company.compparticipationid or dbo.company.compparticipationid null ) part divid = 29
cross apply
evaluate given query each left hand side row, returning first participation company, if 1 or more exist, or first participation in table, if no company participations exist @ all.
ignoring other tables now, should able achieve same result original sql cross apply
projection applies same logic above:
var result = db.companies // include / join on other tables here ... .select(c => new { company = c, participation = db.partipations .firstordefault(p => c.compparticipationid == p.participationid || c.compparticipationid == null) }) // project out final columns company, participation etc.;
the above linq exhibit 1:n performance issue (i.e. lookup in participations
each row of company
). there performance optimizations had, e.g. if many of companies don't have participations (i.e. null compparticipationid) pre-fetch first participation in table , apply in coalesce:
var defaultparticipation = db.partipations.firstordefault(); // ... above participation = db.partipations .firstordefault(p => c.compparticipationid == p.participationid) ?? defaultparticipation;
similarly if there few participations
in table, prefetch of them , key them in dictionary participationid
, , again coalescing default participation if lookup fails (via trygetvalue
or containskey
).
Comments
Post a Comment