I need to convert an SQL query to Linq/Lambda expression, I am trying doing the same but not getting the desired results.
SQL:
SELECT b.*, n.notes
FROM Goal_Allocation_Branch as b
INNER JOIN Goal_Allocation_Product as g
on b.Product = g.ProductID
and b.Year = g.Year
left join Goal_Allocation_Branch_Notes as n
on b.branchnumber = n.branch
and n.year = ddlYear
WHERE b.Year = ddlYear
and g.Show = 1
and branchnumber = ddlBranch
I am new to Linq , I am getting error on Join Clause , and X is not containing any data from first Join
var result = (from br in _DB_Branches.Goal_Allocation_Branches
join pr in _DB_Product.Goal_Allocation_Products on new { br.Product, br.Year } equals new {Product= pr.ProductID, Year= pr.Year }
join n in _DB_Notes.Goal_Allocation_Branch_Notes.Where(n => n.Year == ddlYear) on br.BranchNumber equals n.Branch into Notes
from x in Notes.DefaultIfEmpty()
select new BranchNotesViewModel
{
Year = x.Year,
BranchNumber = x.Branch,
ProductID = x.ProdID
}
).ToList();
Update: My First Join clause initially giving error "The type of one of the expression in Join Clause is incorrect " is resolved, when I Changed On Clause
from
"on new { br.Product, br.Year } equals new {pr.ProductID, pr.Year}"
"on new { br.Product, br.Year } equals new {Product=pr.ProductID,Year= pr.Year}"
still not getting desired results as expected from above SQL query. Please advise..
It should be something like this (see note):
var result =
(from br in _DB_Branches.Goal_Allocation_Branches
join pr in _DB_Product.Goal_Allocation_Products
on br.Product equals pr.ProductID
from n in _DB_Notes.Goal_Allocation_Branch_Notes.Where(x=>
x.branch == br.branchnumber
&& x.year == ddlYear
).DefaultIfEmpty()
where
br.Year == ddlYear
&& and br.Year == pr.Year
&& pr.Show == 1
&& br.branchnumber == ddlBranch
select new BranchNotesViewModel
{
Year = ...,
BranchNumber = ...,
ProductID = ...
}
).ToList();
Note: Change the select, to the properties you want.
Edit: fixed some syntax errors.
I finally figured out the correct answer. Working absolutely fine
var result = (from br in _DB_Branches.Goal_Allocation_Branches
join pr in _DB_Product.Goal_Allocation_Products on new { br.Product, br.Year } equals new { Product = pr.ProductID, Year = pr.Year }
join n in _DB_Notes.Goal_Allocation_Branch_Notes.Where(n=>n.Year==ddlYear) on br.BranchNumber equals n.Branch into Notes
where br.Year==ddlYear
&& pr.Show== true
&& br.BranchNumber==ddlBranch
from x in Notes.DefaultIfEmpty()
select new BranchNotesViewModel
{
Year=x.Year,
BranchNumber=x.Branch,
ProductID=br.Product,
Notes = x.Notes,
//All other fields needed
}
).ToList();
Related
I have Query contains more than one left inner join and returns List
it join with table PayrollTransactions it returns o as it have no data wtuth this condention i need the list to be return in all cases even when the second join is empty
public List<PayrollElementsViewModel> GetAllPayrollRunDetails(int? PayrollrollRunID)
{
IQueryable<PayrollElementsViewModel> List =
(from R in database.PayrollElements
where R.Deleted == false
&& R.PayrollElementsPayrollRunID == PayrollrollRunID
join Emp in database.Employee on R.PayrollElementsIDEmployeeID equals Emp.EmployeeID
into g
from Emp in g.DefaultIfEmpty()
join tran in database.PayrollTransactions on Emp.EmployeeID equals tran.PayrollTransactionsEmployeeID
into g6
from tran in g6.DefaultIfEmpty()
where tran.PayrollTransactionsPayrollRunID == PayrollrollRunID
select new PayrollElementsViewModel
{
PayrollElementsPayrollRunID = PayrollrollRunID,
PayrollElementsEmployeeID = Emp.EmployeeID,
PayrollElementsEmployeeName = Emp.EmployeeName,
PayrollElementsEmployeeFingerPrint = Emp.EmployeeFingerPrint,
PayrollElementsStartDate = R.PayrollElementsStartDate,
PayrollElementsEndDate = R.PayrollElementsEndDate,
PayrollElemenTsransactionsValue = tran.PayrollTransactionsValue
});
var results = List.ToList();
return (results);
}
i need to return List contains data as it returns 0 when the join with payrolltransation if its it contains o
it solved by moving The condition in second join to the select to be
join tran in database.PayrollTransactions on Emp.EmployeeID equals tran.PayrollTransactionsEmployeeID
into g6
from tran in g6.DefaultIfEmpty()
select new PayrollElementsViewModel
{
PayrollElemenTsransactionsValue = tran.PayrollTransactionsPayrollRunID == PayrollrollRunID?tran.PayrollTransactionsValue : 0,
});
I'm trying to join two group by queries to get one results set.
var query = from PP in _db.paymentPlans
join APP in _db.Applications on PP.applicationID equals APP.ApplicationId
join C in _db.Courses on APP.courseID equals C.courseID
where PP.active == true && APP.agentID == agentID
orderby C.courseID ascending
group new {C,PP} by new {C.courseID} into totalRecievable
// Query 1
from PD in _db.paymentDetails
join PP in _db.paymentPlans on PD.paymentPlanID equals PP.paymentPlanID
join APP in _db.Applications on PP.applicationID equals APP.ApplicationId
join C in _db.Courses on APP.courseID equals C.courseID
where PP.active == true && APP.agentID == agentID
orderby C.courseID ascending
group new { C,PD } by new { C.courseID, C.cricosCode, C.courseName } into paymentsCourseWise
// Query 2
select new PdPpAppCourseModel
{
courseID = paymentsCourseWise.Key.courseID,
cricosCode = paymentsCourseWise.Key.cricosCode,
courseName = paymentsCourseWise.Key.courseName,
totalAmount = totalRecievable.Sum(x => x.PP.totalAmount),
paidAmount = paymentsCourseWise.Sum(x => x.PD.paidAmount)
}).ToList();
Total about is taken from query 1 as it should group in payment plan(PP) level.
You can only combine enumerations of the same type, you could project both to a common class and then concatenate them:
var result1 = db1.table.Where(a=>a.value>0).Select( x=> new Foo() { //set props });
var result2 = db2.table.Where(a=>a.value>0).Select( x=> new Foo() { //set props });
var resultSum = result1.Concat(result2);
Similarly you can apply this in your code and join this two groups.
I would like to turn the following SQL query into a LINQ expression (using Entity Framework 6.1). Thus far I have been unable find an acceptable LINQ expression that produces similar results. Any help turning this simple SQL statement into a LINQ express would be appreciated.
SELECT AAG.Id AS GroupId,
A.Id AS ActivityId,
A.Title As Title,
CASE WHEN AA.CompletedOn IS NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Completed,
COALESCE(AAG.PointValue, 0) + SUM(COALESCE(AQ.PointValue, 0)) AS PointTotal
FROM ActivityAssignmentGroup AAG
INNER JOIN ActivityAssignment AA ON AA.GroupId = AAG.Id
INNER JOIN Activity A ON AA.ActivityId = A.Id
LEFT OUTER JOIN ActivityQuestion AQ ON AQ.ActivityId = A.Id
WHERE AAG.AssignedToId = 6
GROUP BY AAG.Id, A.Id, A.Title, CASE WHEN AA.CompletedOn IS NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, COALESCE(AAG.PointValue,0)
Without the LEFT OUTER JOIN portion, the below LINQ statement is partially complete, but I cannot figure out the appropriate syntax to add the LEFT OUTER JOIN condition:
var assignments = await (from g in db.AssignmentGroups.AsNoTracking().Where(x => x.AssignedToId == studentTask.Result.PersonId)
join aa in db.ActivityAssignments.AsNoTracking() on g.Id equals aa.GroupId
join a in db.Activities.AsNoTracking() on aa.ActivityId equals a.Id
select new ActivityListViewModel
{
Id = a.Id,
Points = g.PointValue ?? 0,
Title = a.Title,
GroupId = g.Id,
Complete = (aa.CompletedOn != null)
});
Edit:
Thanks for the response Bob. I attempted to use the DefaultIfEmpty and looked at the resultant SQL query generated by the Entity Framework, but it didn't work. Prior to making this post, this is the LINQ statement I attempted:
var assignments = from g in db.AssignmentGroups.AsNoTracking().Where(x => x.AssignedToId == studentTask.Result.PersonId)
join aa in db.ActivityAssignments.AsNoTracking() on g.Id equals aa.GroupId
join a in db.Activities.AsNoTracking() on aa.ActivityId equals a.Id
from aq in db.ActivityQuestions.Where(q => q.ActivityId == a.Id).DefaultIfEmpty()
group aq by new { ActivityId = aq.ActivityId, Title = a.Title, GroupId = g.Id, Points = g.PointValue ?? 0, Completed = (aa.CompletedOn != null) } into s
select new ActivityListViewModel
{
Id = s.Key.ActivityId,
Points = s.Key.Points + s.Sum(y => y.PointValue ?? 0), //g.PointValue ?? 0,
Title = s.Key.Title,
GroupId = s.Key.GroupId,
Complete = s.Key.Completed
};
Of course, it didn't work either. The result was items missing the Id (ActivityId).
You need DefaultIfEmpty() to convert a join to left outer join, documentition from MSDN here
var assignments = await (from g in db.AssignmentGroups.AsNoTracking().Where(x => x.AssignedToId == studentTask.Result.PersonId)
join aa in db.ActivityAssignments.AsNoTracking() on g.Id equals aa.GroupId
join a1 in db.Activities.AsNoTracking() on aa.ActivityId equals a1.Id into a2
from a in a2.DefaultIfEmpty()
select new ActivityListViewModel
{
Id = a == null ? null : a.Id,
Points = g.PointValue ?? 0,
Title = a == null ? null : a.Title,
GroupId = g.Id,
Complete = (aa.CompletedOn != null)
});
Just to close the loop (and thank you Bob Vale)... the query below works:
var assignments = from g in db.AssignmentGroups.AsNoTracking().Where(x => x.AssignedToId == studentTask.Result.PersonId)
join aa in db.ActivityAssignments.AsNoTracking() on g.Id equals aa.GroupId
join a in db.Activities.AsNoTracking() on aa.ActivityId equals a.Id
from aq in db.ActivityQuestions.Where(q => q.ActivityId == a.Id).DefaultIfEmpty()
group aq by new { ActivityId = a.Id, Title = a.Title, GroupId = g.Id, Points = g.PointValue ?? 0, Completed = (aa.CompletedOn != null) } into s
select new ActivityListViewModel
{
Id = s.Key.ActivityId,
Points = s.Key.Points + s.Sum(y => y.PointValue ?? 0), //g.PointValue ?? 0,
Title = s.Key.Title,
GroupId = s.Key.GroupId,
Complete = s.Key.Completed
};
The issue was the group by condition and using ag.ActivityId when I should have used a.Id.
I am new to Entity, and have a question regarding a LINQ statement.
Below appears my code, it appears with exception to "TotalFoults" field. He always gives 0.
Could anyone help me because all the results in the "TotalFoults" column have a value above zero.
Thank you very much.
var result = (from sr in db.StudentsResult
join F in db.Fouls on sr.Enrollment equals F.Enrollment into F_join
from F in F_join.DefaultIfEmpty()
join S in db.Students on sr.Enrollment equals S.Enrollment into A_join
from A in A_join.DefaultIfEmpty()
where
F.Day != null
group new { sr, s } by new
{
sr.Enrollment ,
sr.Name,
sr.Number,
sr.Classes,
s.Discount
} into g
orderby
g.Key.Classes,
g.Key.Number,
g.Key.Name
select new frequencyMod()
{
Enrollment = g.Key.Enrollment ,
StudentName = g.Key.Name,
StudentFile= g.Key.Number,
Classes = g.Key.Classes,
TotalFoults = (from m0 in db.Foults
where
m0.Enrollment == g.Key.Enrollment
group m0 by new
{
m0.Enrollment
} into a
select new
{
Total = a.Sum(p => p.Foults)
}).FirstOrDefault().Total
}).ToList();
Im just new in MVC3 and have a little problem. I want to convert this SQL statement into Linq. Can anyone please help me with this problem, here is my sql Statement:
SELECT a.payment_ref_no,
c.institution_name,
a.check_date,
batchstatus = CASE
WHEN d.mccount = Count(b.check_detail_no) THEN
'Completed'
WHEN d.mccount IS NULL THEN 'Approved'
WHEN d.mccount < Count(b.check_detail_no) THEN
'Partially Processed'
END,
noofpayments=Count(b.check_detail_no),
totalamount=Sum(b.check_amount),
d.mccount
FROM check_request a
JOIN check_details b
ON a.request_ref_no = b.request_ref_no
JOIN institution c
ON a.company_code = c.company_code
LEFT JOIN vw_batchstatus d
ON a.request_ref_no = d.request_ref_no
WHERE a.payment_ref_no IS NOT NULL
GROUP BY a.payment_ref_no,
a.check_date,
c.institution_name,
d.mccount
Done mostly from memory, may be some issues, but should be a step in the right direction for you.
var test = from a in check_request
join b in check_details on a.request_ref_no equals b.request_ref_no
join c in institution on a.company_code equals c.company_code
join d in vw_batchstatus on a.request_ref_no equals d.request_ref_no into dvwinner
from d in dvwinner.DefaultIfEmpty()
where a.payment_ref.HasValue
group a by new (a.payment_ref_no, a.check_date, c.institution_name, d.mccount) into gr1
select new {
ref_no = a.payment_ref_no,
inst_name = c.institution_name,
check_date = a.check_date,
batstat = !d.mccount.HasValue ? 'Approved' : d.mccount == b.check_detail_no.Count() ? 'Completed' : 'Partially Processed',
noofpayments = b.check_detail_no.Count(),
ttlamount = gr1.Sum(p=>p.check_amount),
mccount = d.mccount
};
Thanks Kyle for the help.I finally solved my own problems, here is the linq of my sql statement
var test = from a in CHECK_REQUESTs
join b in CHECK_DETAILS on a.REQUEST_REF_NO equals b.REQUEST_REF_NO
join c in INSTITUTIONs on a.COMPANY_CODE equals c.COMPANY_CODE
join d in Vw_BatchStatus on a.REQUEST_REF_NO equals d.REQUEST_REF_NO into t from rt in t.DefaultIfEmpty()
where a.PAYMENT_REF_NO != string.Empty
let institutionName = (string)c.Institution_Name
let mcCount = (int)rt.Mccount
group b by new
{
a.PAYMENT_REF_NO,
a.Check_Date,
institutionName,
mcCount
} into gr1
select new
{
gr1.Key.PAYMENT_REF_NO,
gr1.Key.institutionName,
gr1.Key.Check_Date,
batchstatus = (gr1.Key.mcCount == gr1.Count()) ? "Completed" :
(gr1.Key.mcCount < gr1.Count()) ? "Partially Processed":
(gr1.Key.mcCount == null ) ? "Approved" : " ",
noofpayments = gr1.Count(),
totalamount = gr1.Sum(c => c.Check_Amount)
};