What will be the LINQ query for the below SQL Query - sql

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 }

Related

I need to transform a SQL query with inner joins to Linq in Entity Framework

I am very new to translating queries to entity, I don't know how to replace that query into linq in my code
select
brules.rule_description, brules.user_story_number,
so.source_name,
count(dlog.row_id) as error_count,
cast(execution_date as date) as execution_date
from
br.lk_business_rules brules
inner join
br.business_rules_detailed_log dlog on dlog.user_story_number = brules.user_story_number
inner join
br.lk_business_rules_source so on so.source_id = source_id_fk
where
brules.status_id_fk = 3
group by
brules.rule_description, brules.user_story_number,
so.source_name, cast(execution_date as date)
order by
brules.rule_description
i tried this:
var query = from br in _context.Lk_business_rules
join detLog in _context.Business_rules_detailed_log
on br.User_story_number equals detLog.User_story_number
join source in _context.Lk_business_rules_source
on detLog.Source_id equals source.Source_id
where br.Status_id_fk == 3
select new
{
Business_rule_description = br.Rule_description,
Business_rule_storynumber = br.User_story_number,
Source = source.Source_name,
Error_count = detLog.Row_id.Count,
Date = detLog.Execution_date
};
but not succed

how to convert left join SQL script to Linq script?

How can I convert left join to linq script. I have a T-SQL like this:
SELECT
es.StandardID,
COUNT(DISTINCT esc.StandardCourseID) AS CourseIDCount,
COUNT(DISTINCT esp.StandardPostID) AS PostIDCount
FROM EduStandards AS es
LEFT JOIN EduStandardCourses AS esc
ON es.StandardID = esc.StandardID
LEFT JOIN EduStandardPosts AS esp
ON es.StandardID = esp.StandardID
GROUP BY es.StandardID
That I want to convert this to linq.
Following is the query with left join that is replica of your query in linq.
var query = (from es in dbContext.EduStandards
join esc in dbContext.EduStandardCourses on es.StandardID equals esc.StandardID into ssc
from esc in ssc.DefaultIfEmpty()
join esp in dbContext.EduStandardPosts on es.StandardID equals esp.StandardID into ssp
from esp in ssp.DefaultIfEmpty()
select new { StandardId = es.StandardID, CourseCount = ssc.Count(), PostCount = ssp.Count() }).Distinct().ToList();
But I think we need not to apply left join in linq to calculate count. Following optimized linq query will return same result.
var query2 = (from es in dbContext.EduStandards
join esc in dbContext.EduStandardCourses on es.StandardID equals esc.StandardID into ssc
join esp in dbContext.EduStandardPosts on es.StandardID equals esp.StandardID into ssp
select new { StandardId = es.StandardID, CourseCount = ssc.Count(), PostCount = ssp.Count() });
This is what I've come up with
var query = from es in db.EduStandards
join esc1 in db.EduStandardCourses
on es.StandardId equals esc1.StandardId into esc
from c in esc.DefaultIfEmpty()
join esp1 in db.EduStandardPosts
on es.StandardId equals esp1.StandardId into esp
from p in esp.DefaultIfEmpty()
group new { es.StandardId, Course = c, Post = p } by es.StandardId into g
select new
{
StandardId = g.Key,
CourseIdCount = g.Where(x => x.Course != null).Count(),
PostIdCount = g.Where(x => x.Post != null).Count(),
};
However, I'm not entirely sure if it'll work for EF.
You could always do something like this:
var query = from es in db.EduStandards
select new
{
es.StandardId,
CourseIdCount = db.EduStandardCourses.Where(esc => esc.StandardId == es.StandardId).Distinct().Count(),
PostIdCount = db.EduStandardPosts.Where(esp => esp.StandardId == es.StandardId).Distinct().Count()
};
Also, I can't attest to the performance of either one of these queries due to the lack of knowledge of your database.

Linq To entity no full join issue

I have the following SQL script that gives me the results i'm after , i'm having trouble replicating the full join and the count distinct on the activities count:
select ActivityCount,ActivityComplete, ImagePath, SubjectTitle from
(select
Count(Distinct(Act.[ActivityID])) as ActivityCount,
Sum(Case when (([OutcomeID] = 1 or [OutcomeID] = 3) and AOU.ActivityUserID=1 ) Then 1 Else 0 End) As ActivityComplete,
Sub.[SubjectImageName] as ImagePath,
Sub.SubjectTitle as SubjectTitle
from [dbo].[UserActivityOutcome] AOU
full join Activity Act on Act.[ActivityID] = AOU.[ActivityID]
left join Category Cat on Act.[CategoryID] = Cat.[CategoryID]
left join Subject Sub on Cat.[SubjectID] = Sub.[SubjectID]
group by Sub.SubjectTitle, Sub.[SubjectImageName]
) as x
results:
</head>
<body><div class="spacer"><table id="t1"><tr><td class="typeheader" colspan="4">Result Set (2 items)</td></tr><tr><th title="System.Int32">ActivityCount</th><th title="System.Int32">ActivityComplete</th><th title="System.String">ImagePath</th><th title="System.String">SubjectTitle</th></tr><tr><td class="n">25</td><td class="n">3</td><td>Subject 1.png</td><td>Subject 1</td></tr><tr><td class="n">1</td><td class="n">1</td><td>Subject 2.png</td><td>Subject 2</td></tr><tr><td title="Total=26
Average=13" class="columntotal">26</td><td title="Total=4
Average=2" class="columntotal">4</td><td title="Totals" class="columntotal"></td><td title="Totals" class="columntotal"></td></tr></table></div></body>
</html>
my linq looks like this:
from x in (
(from Act in Activities
join AOU in UserActivityOutcomes on Act.ActivityID equals AOU.ActivityID into AOU_join
from AOU in AOU_join.DefaultIfEmpty()
join ActNA in Activities on AOU.ActivityID equals ActNA.ActivityID into ActNA_join
from ActNA in ActNA_join.DefaultIfEmpty()
join Cat in Categories on AOU.Activity.CategoryID equals Cat.CategoryID into Cat_join
from Cat in Cat_join.DefaultIfEmpty()
join Sub in Subjects on Cat.SubjectID equals Sub.SubjectID into Sub_join
from Sub in Sub_join.DefaultIfEmpty()
group new {Sub, AOU, Act,ActNA} by new {
Sub.SubjectTitle,
Sub.SubjectImageName
} into g
select new {
ActivityCount = g.Distinct().Count(), //g.Count(),
ActivityComplete = g.Sum(p => (
(p.AOU.OutcomeID == 1 ||
p.AOU.OutcomeID == 3)&&
p.AOU.ActivityUserID == 23 ? 1 : 0)),
ImagePath = g.Key.SubjectImageName,
SubjectTitle = g.Key.SubjectTitle
}))
select new {
x.ActivityCount,
x.ActivityComplete,
x.ImagePath,
x.SubjectTitle
}
LINQ full outer join is tricky. The only way it could be simulated is by union of left outer join and right antijoin. Here is IMO the LINQ equivalent of your SQL query:
var query =
// AOU full join Act
(from e in (from AOU in UserActivityOutcomes
join Act in Activities on AOU.ActivityID equals Act.ActivityID into Act_join
from Act in Act_join.DefaultIfEmpty()
select new { AOU, Act })
.Concat
(from Act in Activities
join AOU in UserActivityOutcomes on Act.ActivityID equals AOU.ActivityID into AOU_join
from AOU in AOU_join.DefaultIfEmpty()
where AOU == null
select new { AOU, Act })
let AOU = e.AOU
let Act = e.Act
// left join Cat
join Cat in Categories on Act.CategoryID equals Cat.CategoryID into Cat_join
from Cat in Cat_join.DefaultIfEmpty()
// left join Sub
join Sub in Subjects on Cat.SubjectID equals Sub.SubjectID into Sub_join
from Sub in Sub_join.DefaultIfEmpty()
group new { Sub, AOU, Act } by new { Sub.SubjectTitle, Sub.SubjectImageName } into g
select new
{
ActivityCount = g.Where(e => e.Act != null).Select(e => e.Act.ActivityID).Distinct().Count(),
ActivityComplete = g.Sum(e => (e.AOU.OutcomeID == 1 || e.AOU.OutcomeID == 3) && e.AOU.ActivityUserID == 1 ? 1 : 0),
ImagePath = g.Key.SubjectImageName,
SubjectTitle = g.Key.SubjectTitle
};

Left outter join linq

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

SQL Query in LINQ to Entities

Can anyone tell me,how to write this query in LINQ?
select a.UTP_NAME, b.UPS_NAME, c.USS_NAME from
TB_UTILIDADE_PUBLIC_UTP a inner join
TB_UTILIDADE_PUBLIC_SECTOR_UPS b on
a.UPS_ID = b.UPS_ID
inner join TB_UTILIDADE_PUBLIC_SUBSECTOR_USS c
on a.USS_ID = c.USS_ID and a.UPS_ID = c.UPS_ID /* IMPORTANT LINE! */
Thanks.
Creating a new anonymous type allows you to join with multiple criteria
var query = from a in context.TB_UTILIDADE_PUBLIC_UTP
join b in context.TB_UTILIDADE_PUBLIC_SECTOR_UPS
on a.UPS_ID equals b.UPS_ID
join c in context.TB_UTILIDADE_PUBLIC_SUBSECTOR_USS
on new { a.USS_ID, a.UPS_ID } equals new { c.USS_ID, c.UPS_ID }
select new
{
a.UTP_NAME,
b.UPS_NAME,
c.USS_NAME
};