I want to set inner join in linq query
Here is my code,
var JoinUsingMS = from emp in _productRepository.Table
join address in _purchaseReminderRepository.Table
on new { c1 = emp.VendorId, c2 = emp.Name } equals new { c1 = address.VendorId, c2 = address.Product } into bp_sm
from c in bp_sm.DefaultIfEmpty()
where emp.Published == true
select emp;
From this query I am getting left join (track by doing debug). While I think so this query is perfect for inner join (reference link As Per This Solution) still output getting the left join
Below updated query for the inner joins:
var JoinUsingMS = from emp in _productRepository.Table
join address in _purchaseReminderRepository.Table
on new { c1 = emp.VendorId, c2 = emp.Name }
equals new { c1 = address.VendorId, c2 = address.Product }
where emp.Published == true
select emp;
Simple. Remove the DefaultIfEmpty line. That's what creates the left join clause:
var JoinUsingMS =
from emp in _productRepository.Table
join address in _purchaseReminderRepository.Table
on new { c1 = emp.VendorId, c2 = emp.Name } equals new { c1 = address.VendorId, c2 = address.Product } // into bp_sm
// from c in bp_sm.DefaultIfEmpty()
where emp.Published == true
select emp;
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 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();
How can I use left outer join in LINQ for the following SQL query?
SELECT a.EventID, a.PrizeId, b.PrizeName, b.PrizeValue, c.FightID, c.Winnerid, c.WinnerName
FROM tblUserprize a
JOIN tblPrizeDetails b
ON a.PrizeId=b.PrizeId
LEFT OUTER JOIN tblWinnersList c
ON a.EventID=c.EventID AND a.PrizeId=c.PrizeId AND c.FightID = 1534
WHERE a.EventID = 1320
It should look like this:
var userPrize = (
from a in tblUserprize
join b in tblPrizeDetails on a.PrizeId equals b.PrizeId
join c in tblWinnersList on new { a.EventID, a.PrizeId } equals new { c.EventID, c.PrizeId } into joinedTables
from item in joinedTables.DefaultIfEmpty()
where a.EventID == 1320 && item.FightID == 1534
select new
{
a.EventID,
a.PrizeId,
b.PrizeName,
b.PrizeValue,
item.FightID,
item.Winnerid,
item.WinnerName
});
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.
Can someone explain me why this does not work.
private void AdditionalLoad(List<PersonTypePerson> ptps)
{
using(var _context = new SPIS_Entities())
{
var m = (from ptp in ptps.Where(xx => xx.PersonID == _Person.ID)//_context.PersonTypePerson //
join pt in _context.PersonType on ptp.PersonTypeID equals pt.ID
join pta in _context.PersonTypeAttriubute.Where(p => p.active) on pt.ID equals pta.PersontypeID
select new { persontypeatribute = pta, availableatribute = pta.Attribute }).ToList();
var x = from ii in _context.InformationItem.Where(p=>p.PersonID ==_Person.ID)
join pta in _context.PersonTypeAttriubute.Where(p => p.active) on ii.PersonTypeAtributeID equals pta.ID
select new { persontype = pta.PersonType, attribute = pta.Attribute, information = ii };
var z = (from all in m
join fill in x on all.persontypeatribute.AttributeID equals fill.attribute.ID into ps
from fill in ps.DefaultIfEmpty()
select new
{
persontype = all.persontypeatribute.PersonType, //fill.persontype,
available = all.availableatribute,
attribute = fill.attribute,
information = fill.information
}).ToList();
}
}
The funniest thing is that I get a query result from "m" and "x". When it comes to the point to make the left join ("z") it breaks and throws a nullException, object reference not set to an instance of an object.