I need to translate that query to Entity Framework, can someone help me ?
select distinct
rap.AtracacaoData Atracacao,
loc.Nome_Local Local,
nav.Nome Navio,
nav.Navio_ID ViagemNavio,
'DT ' TransferenciaTipo,
edt.Numero TransferenciaNumero,
loct.Local Terminal
from
terminal..blalf bl (nolock)
inner join
terminal..navios nav (nolock) on nav.navio_id = bl.navio
inner join
terminal..avisochegada rap (nolock) on rap.Numero_Viagem_Ano = nav.Viagem_Ano_AVC
inner join
terminal..localatracalf loc (nolock) on loc.codigo_local = rap.armazem
inner join
tresos..vw_autorizacaorecebimento_navio autnav (nolock) on autnav.viagemnavio = nav.navio_id
and autnav.tipo = 2
inner join
tresos..edt edt (nolock) on edt.ID = autnav.DeclaracaoTransitoEntrada
inner join
tresos..localidades loct (nolock) on loct.ID = bl.terminal
union
select distinct
rap.AtracacaoData Atracacao,
loc.Nome_Local Local,
nav.Nome Navio,
nav.Navio_ID ViagemNavio,
'DTA ' TranferenciaTipo,
edt.Numero TransferenciaNumero,
loct.Local Terminal
from
terminal..blalf bl (nolock)
inner join
terminal..navios nav (nolock) on nav.navio_id = bl.navio
inner join
terminal..avisochegada rap (nolock) on rap.Numero_Viagem_Ano = nav.Viagem_Ano_AVC
inner join
terminal..localatracalf loc (nolock) on loc.codigo_local = rap.armazem
inner join
tresos..vw_autorizacaorecebimento_navio autnav (nolock) on autnav.viagemnavio = nav.navio_id
and autnav.tipo = 3
inner join
tresos..edta edt (nolock) on edt.ID = autnav.DeclaracaoTransitoEntrada
inner join
tresos..localidades loct (nolock) on loct.ID = bl.terminal
union
select distinct
rap.AtracacaoData Atracacao,
loc.Nome_Local Local,
nav.Nome Navio,
nav.Navio_ID ViagemNavio,
'PCI ' TranferenciaTipo,
edt.Numero TransferenciaNumero,
loct.Local Terminal
from
terminal..blalf bl (nolock)
inner join
terminal..navios nav (nolock) on nav.navio_id = bl.navio
inner join
terminal..avisochegada rap (nolock) on rap.Numero_Viagem_Ano = nav.Viagem_Ano_AVC
inner join
terminal..localatracalf loc (nolock) on loc.codigo_local = rap.armazem
inner join
tresos..vw_autorizacaorecebimento_navio autnav (nolock) on autnav.viagemnavio = nav.navio_id
and autnav.tipo = 4
inner join
tresos..eprc edt (nolock) on edt.ID = autnav.DeclaracaoTransitoEntrada
inner join
tresos..localidades loct (nolock) on loct.ID = bl.terminal
I tried to do but I couldn't do it.
First, you need an Entity Framework model that maps to your SQL structure. Hopefully you already have that. I'm assuming you do.
Second, you should create a DTO that has the properties your query will return:
public class ASensibleNameInYourDomain {
public ? Atracaco {get; set;}
public string Local {get; set;}
...
}
Third, you write a function that takes your EF DbContext and the query params, and returns a list of your DTO. It looks like your SQL is the same query repeated so I'd do:
public List<ASensibleNameInYourDomain> LoadFlightInfo(DbContext context, int autNavTipo, string transfericaTipo) {
return context.Blalf.Select(blaf=>
new ASensibleNameInYourDomain {
Atracacao=blaf.Navios.Avisochegada.AtracacaoData,
Local=blaf.Navios.Avisochegada.Localatracalf.Nome_Local,
Navio=blaf.Navios.Nome,
ViagemNavio=blaf.Navios.Navio_ID,
TransferenciaTipo=transfericaTipo,
TransferenciaNumero=blaf.Navios.Autorizacaorecebimento_navio.Numero,
Terminal=blaf.Localidades.Local
}
).Where(blaf=> blaf.Navios.Autorizacaorecebimento_navio.Tipo == autNavTipo)
.Distinct()
.ToList()
}
And then call it like so
public List<ASensibleNameInYourDomain> GetFlights(DbContext context) {
var result = LoadFlightInfo(context, 2, "DT");
result.addRange(LoadFlightInfo(context, 3, "DTA"));
result.addRange(LoadFlightInfo(context, 4, "PCI"));
return result
}
I think that'll do it, been a while since I did any C#...
Related
Code
_doctorRepository.Where(t => t.Id == doctorId).ProjectTo<EmploymentDTO>(_mapper.ConfigurationProvider).FirstOrDefault()
Mapping configuration
// doctor have Navigation property Hospital
CreateMap<Doctor, EmploymentDTO>().IncludeMembers(t => t.Hospital);
CreateMap<Hospital, EmploymentDTO>();
Expected behavior
SELECT TOP(1) [d].[Id], [d].[DepartmentId], [d].[DepartmentOther], [d].[DepartmentOtherCN], [d].[HospitalId], [d].[PositionId], [d].[PositionOther], [d].[PositionOtherCN], [d].[RankId], [d].[RankOther], [d].[RankOtherCN], [h].[City], [h].[Country], [h].[UniversityAffiliated], [h].[HospitalName], [h].[Province], [h].[CityCN], [h].[CountryCN], [h].[UniversityAffiliatedCN], [h].[HospitalNameCN], [h].[ProvinceCN]
FROM [Doctor] AS [d] WITH (NOLOCK)
LEFT JOIN [Hospital] AS [h] WITH (NOLOCK) ON [d].[HospitalId] = [h].[Id]
WHERE [d].[Id] = #__doctorId_0
Actual behavior :
not left join hospital Table
SELECT TOP(1) [d].[DepartmentId], [d].[DepartmentOther], [d].[DepartmentOtherCN], [d].[HospitalId], [d].[Id], [d].[PositionId], [d].[PositionOther], [d].[PositionOtherCN], [d].[RankId], [d].[RankOther], [d].[RankOtherCN]
FROM [Doctor] AS [d] WITH (NOLOCK)
WHERE [d].[Id] = #__doctorId_0
I have inherited an application that is using the drupal filtering system to find results. The user can select to search the 'campus_location' column but when they enter multiple variables, it adds an AND between the condition.
Here is the printed version of the query generated by drupal:
SELECT * FROM champs c INNER JOIN users u ON u.uid = c.uid LEFT OUTER JOIN champs_rsvp r
ON r.uid = c.uid LEFT OUTER JOIN champs_checklists cl
ON cl.id = c.checklist_id LEFT OUTER JOIN node en
ON en.uid = u.uid AND en.type = 'getting_started_event'
LEFT OUTER JOIN node sn ON sn.uid = u.uid
AND sn.type = 'success_story'
LEFT OUTER JOIN champs_action_steps cas
ON cas.uid = u.uid
WHERE ( (c.campus_location LIKE 'Flint' ESCAPE '\\') )
**AND**( (c.campus_location LIKE 'Ann Arbor' ESCAPE '\\') )
I need the last AND to be an OR so it looks like this:
SELECT * FROM champs c INNER JOIN users u ON u.uid = c.uid LEFT OUTER JOIN champs_rsvp r
ON r.uid = c.uid LEFT OUTER JOIN champs_checklists cl
ON cl.id = c.checklist_id LEFT OUTER JOIN node en
ON en.uid = u.uid AND en.type = 'getting_started_event'
LEFT OUTER JOIN node sn ON sn.uid = u.uid
AND sn.type = 'success_story'
LEFT OUTER JOIN champs_action_steps cas
ON cas.uid = u.uid
WHERE ( (c.campus_location LIKE 'Flint' ESCAPE '\\') )
OR( (c.campus_location LIKE 'Ann Arbor' ESCAPE '\\') )
Which produces the correct results.
Here is the code that I inherited where it looks over the words in the search box. I just can't seem to figure out where it is adding the variables where it is putting the AND.
$words = explode(",", $_SESSION['form_state']['values']['filter']);
foreach($words as $word)
{
$or = db_or();
foreach($cols as $col)
{
$table = 'c';
if(in_array($col, array('completed_date', 'score')))
$table = 'cl';
elseif(in_array($col, array('name', 'mail')))
$table = 'u';
elseif($col == 'date')
$table = 'r';
elseif(in_array($col, array('announce', 'num_success_stories', 'num_action_steps'))) //can't put these in WHERE clause. Need to go in HAVING.
continue;
echo $word;
$or = $or->condition($table . '.' . $col, champs_make_like_sql($word), 'LIKE');
}
$result = $query->condition($or);
}
How do i change the training events into a left outer join in training events im very basic at linq so excuse my ignorance its not retrieve records that don't have any trainnevent reference attached to it
var q = from need in pamsEntities.EmployeeLearningNeeds
join Employee e in pamsEntities.Employees on need.EmployeeId equals e.emp_no
join tevent in pamsEntities.TrainingEvents on need.TrainingEventId equals tevent.RecordId
where need.EmployeeId == employeeId
where need.TargetDate >= startdate
where need.TargetDate <= enddate
orderby need.TargetDat
It's best to use where in combination with DefaultIfEmpty.
See here: LEFT JOIN in LINQ to entities?
var query2 = (
from users in Repo.T_Benutzer
from mappings in Repo.T_Benutzer_Benutzergruppen.Where(mapping => mapping.BEBG_BE == users.BE_ID).DefaultIfEmpty()
from groups in Repo.T_Benutzergruppen.Where(gruppe => gruppe.ID == mappings.BEBG_BG).DefaultIfEmpty()
//where users.BE_Name.Contains(keyword)
// //|| mappings.BEBG_BE.Equals(666)
//|| mappings.BEBG_BE == 666
//|| groups.Name.Contains(keyword)
select new
{
UserId = users.BE_ID
,UserName = users.BE_User
,UserGroupId = mappings.BEBG_BG
,GroupName = groups.Name
}
);
var xy = (query2).ToList();
Which is equivalent to this select statement:
SELECT
T_Benutzer.BE_User
,T_Benutzer_Benutzergruppen.BEBG_BE
-- etc.
FROM T_Benutzer
LEFT JOIN T_Benutzer_Benutzergruppen
ON T_Benutzer_Benutzergruppen.BEBG_BE = T_Benutzer.BE_ID
LEFT JOIN T_Benutzergruppen
ON T_Benutzergruppen.ID = T_Benutzer_Benutzergruppen.BEBG_BG
SELECT t_PersonalInformation.personalInformation_Name, t_PersonalInformation.personalInformation_PresentAddress,
t_Applicant.applicant_TotalExperience,
t_Experience.experience_CompanyName,
t_Experience.experience_Responsibilities,
t_Training.training_TitleDetails
FROM t_Applicant LEFT OUTER JOIN
t_PersonalInformation ON t_Applicant.applicant_user_ID = t_PersonalInformation.personalInformation_applicant_ID
LEFT OUTER JOIN
t_Experience ON t_Applicant.applicant_user_ID = t_Experience.experience_applicant_ID
LEFT OUTER JOIN
t_Training ON t_Applicant.applicant_user_ID = t_Training.training_applicant_ID
WHERE (t_Applicant.applicant_user_ID = 'hasib789')
I am working with C# with vs2008 for a asp.net application
It is depend on what mapping do you have.
For example it can be:
var result =
from a in DataContext.Applicant
join pi in DataContext.PersonalInformation on a.applicant_user_ID equals pi.personalInformation_applicant_ID
join e in DataContext.Experience on a.applicant_user_ID equals e.experience_applicant_ID
join t in DataContext.Training on a.applicant_user_ID equals t.training_applicant_ID
where a.applicant_user_ID == 'hasib789'
select new { personalInformation_Name = pi.personalInformation_Name, personalInformation_PresentAddress = pi.personalInformation_PresentAddress, applicant_TotalExperience = a.applicant_TotalExperience, experience_CompanyName = e.experience_CompanyName, experience_Responsibilities = e.experience_Responsibilities, training_TitleDetails = t.training_TitleDetails }
[NUnit.Framework.Test]
public void Test2()
{
NHibernate.ISession session = Z.Core.NHibernateCore.NHibernateHelper.GetCurrentSession();
var crit = session.CreateCriteria("_School");
crit.CreateCriteria("_ListStudent", "__ListStudent", NHibernate.SqlCommand.JoinType.LeftOuterJoin);
crit.Add(NHibernate.Criterion.Expression.Eq("__ListStudent.Name", "Abc"));
var list = crit.List();
Console.Write(list.Count);
}
NHibernate:
SELECT * FROM Tst_School this_ left outer join Tst_Student liststud1_ on this_.Guid=liststud1_.Guid WHERE liststud1_.Name = 'Abc'
How to create sql:
SELECT * FROM Tst_School this_ left outer join Tst_Student liststud1_ on this_.Guid=liststud1_.Guid AND liststud1_.Name = 'Abc'
Thanks
You should check WITH clause in HQL. I don't know if it's possible in CriteriaQuery.
http://nhforge.org/blogs/nhibernate/archive/2009/05/17/nhibernate-2-1-0-hql-with-clause.aspx