following linq performing left outer join instead of inner join - linq

I cannot see where the problem lies with the following code. I am trying to retrieve those employees who are named as responsibles for certain vacancie. I have about 20 vacancies in my DB assigned to some 16 employees and about 1801 employee records in the employees table. The code always returns a result with 1801 entries.
from emp in container.Employees
join p in container.Vacancies
on emp.EMPID equals p.ResponsibleOfficer into j
group j by new {k1=emp.EMPID,k2=emp.NAME} into g
select new { EmpId = g.Key.k1, Name = g.Key.k2 , Count = g.Count()}
I want something similar to this
select emp.EmpId,emp.Name,Count(*) as count
from Vacancies p, Employees e
where p.ResponsibleOfficer=e.EmpId
group by e.EmpId,e.Name
any help is much appreciated. thanks

You're using join ... into. That will always return a single result for each element of the original sequence, even if there are no matches in the right sequence.
You can filter out entries with no elements in j using a where clause:
from emp in container.Employees
join p in container.Vacancies
on emp.EMPID equals p.ResponsibleOfficer into j
where j.Any()
group j by new {k1=emp.EMPID,k2=emp.NAME} into g
select new { EmpId = g.Key.k1, Name = g.Key.k2 , Count = g.Count()}
Or you could just use an inner join to start with - but I don't understand your current grouping well enough to see what you're trying to do. What is your group by clause for?
EDIT: If it was really just to group by employee, you're already doing that. You can change the code to:
from emp in container.Employees
join p in container.Vacancies
on emp.EMPID equals p.ResponsibleOfficer into j
where j.Any()
select new { Employee = emp, Count = j.Count()}
Basically, after the join you've got two range variables in scope: emp (the "current" employee) and j (all the relevant vacancies matching that employee). You're just trying to count j for each employee, right?

I'm using lambda, but works:
container
.Employees
.Join(container.Vacancies, l => l.EmpId, e => e.ResponsibleOfficer, (l, e) => new { l.EmpId, l.Name })
.GroupBy(g => new { g.EmpId, g.Name })
.Select(s => new { EmpId = s.Key.EmpId, Name = s.Key.Name, Count = s.Count() });

Related

EF linq query working in linqpad but not in the App

I have creatred a query in linqpad and it works but when i try to use it in my blazor app the app throws an error.
I have three tables, tblOpportunity, tblOppStatus and lkpStatus
and an opportunity can have many status's depending on how mature the enquiry is. So i need to get all the latestest status for each opportunity. I also want to be able to filter the dataset so i get only opportunities with staus of x, y and z
void Main()
{
var output=from o in TblOpportunities
join sub in (
//get the latest status ID for the from the joining table
from smax in TblOppStatuses
group smax by smax.OpportunityID
into g
select new
{
OName = g.Key,
MaxS = (from t2 in g select t2.OppStatusID).Max()
})
on o.OpportunityID equals sub.OName
join st in TblOppStatuses on sub.MaxS equals st.OppStatusID
//get the statu sname form the lookup table
join lst in Lkp_Statuses on st.StatusID equals lst.StatusID
join c in TblClients on o.ClientID equals c.ClientID
select new
{
c.ClientName,
o.OpportunityName,
sub.MaxS,
lst.Status,
lst.StatusID
};
int[] filter = { -1, 62};
output.Where(of=>filter.Contains(of.StatusID))
.Dump();
}
The error that comes in the subquery
MaxS = (from t2 in g select t2.OppStatusID).Max()
if i comment this out the query runs but doesn't give me what i want. Can anyone advise what i am doing wrong As I say it works fine in Linqpad.

Linq Group by / Distinct with Join table

i plan to join 2 table, and get the distinct value of language column. How should i achieve that in Linq? I try add 'group' but no luck. Besides, i want to select s value too together with r distinct language value.
My code:
public ActionResult QuestionLink(int Survey_ID)
{
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group r.language << this is not work **
select r;
return PartialView(query.ToList());
}
This is what in MoreLinq is called DistinctBy. But if that method works on IEnumerable, so you can't use it in an EF query. But you can use the same approach:
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group new { r, s } by r.language into grp
select grp.FirstOrDefault();
But I wonder if this really is what you want. The result depends on the ordering of languages that the database happens to return. I think you should add a predicate for a specific language and remove the grouping:
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
&& r.language == someVariable
select new { r, s };
You can do like this:
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group new {r, s} by r.language into rg
select rg.Key;

Linq query joining with a subquery

I am trying to reproduce a SQL query using a LINQ to Entities query. The following SQL works fine, I just don't see how to do it in LINQ. I have tried for a few hours today but I'm just missing something.
SELECT
h.ReqID,
rs.RoutingSection
FROM ReqHeader h
JOIN ReqRoutings rr ON rr.ReqRoutingID = (SELECT TOP 1 r1.ReqRoutingID
FROM ReqRoutings r1
WHERE r1.ReqID = h.ReqID
ORDER BY r1.ReqRoutingID desc)
JOIN ReqRoutingSections rs ON rs.RoutingSectionID = rr.RoutingSectionID
Edit***
I was able to get this working after looking at other examples including the one provided her by Miki. Here is the code that works for me:
First I created a query called route to hold the top record I needed to join to
var route = (from rr in context.ReqRoutings
where rr.ReqID == id
orderby rr.ID descending
select rr).Take(1);
I was then able to join to my requisitions table and the ReqRoutings lookup table
var header = (from h in context.ReqHeaders
join r in route on h.ID equals r.ReqID
join rs in context.ReqRoutingSections on r.RoutingSectionID equals rs.ID
where h.ID == id
select {ReqID = h.ID,
RoutingSection = rs.RoutingSection}
I am using Northwnd sample database
Customers,Orders,Employees table
Here I am getting top 1 order group by customer and order's employeeid
Please let me know If this is matching with your requirement or not
var ord = from o in NDC.Orders
orderby o.OrderID descending
group o by o.CustomerID into g
select new {CustomerID=g.Key,Order=g.OrderByDescending(s=>s.OrderID).First() };
var res1 = from o in ord
join emp in NDC.Employees
on o.Order.EmployeeID equals emp.EmployeeID into oemp
select new {Order=o.Order,employee=oemp };
Response.Write(res1.ToList().Count);
foreach (var order in res1)
{
Response.Write(order.Order.CustomerID + "," +
order.Order.OrderID + ","+
order.Order.EmployeeID+"<br/>");
}
// Above code is working .I have tried to convert your query to linq and replace your datacontext name with 'NDC'
var ord = from rr in NDC.ReqRoutings
orderby rr.ReqRoutingID descending
group rr by rr.ReqID into g
select new
{
ReqID = g.Key,
ReqRoutings = g.OrderByDescending(s => s.ReqRoutingID).First()
};
var res1 = from o in ord
join emp in NDC.ReqRoutingSections on o.ReqRoutings.RoutingSectionID
equals emp.RoutingSectionID into oemp
select new { ReqRoutings = o.ReqRoutings, employee = oemp };
Response.Write(res1.ToList().Count);
foreach (var order in res1)
{
Response.Write(order.ReqRoutings.ReqID + "," +
order.ReqRoutings.ReqRoutingID + "," +
order.ReqRoutings.RoutingSectionID + "<br/>");
}
Please let know if it is help you or not

Group by, Sum, Join in Linq

I have this simple sql query:
select c.LastName, Sum(b.Debit)- Sum(b.Credit) as OpenBalance from Balance as b
inner join Job as j on (b.Job = j.ID)
inner join Client as c on (j.Client = c.ID)
Group By c.LastName
and I am trying to convert it to work in linq like this:
from b in Balance
join j in Job on b.Job equals j.ID
join c in Client on j.Client equals c.ID
group b by new { c.LastName } into g
select new {
Name = c.Lastname,
OpenBalance = g.Sum(t1 => t1.Credit)
}
but when I try to run it in LINQPad I get the following message:
The name 'c' does not exist in the
current context
and it highlights c.Lastname in select new statement.
Any help on this will be greatly appreciated.
Thank you.
Well, you've grouped b by c.LastName. So after the grouping operation, you're dealing with g which is a grouping with the element type being the type of b, and the key type being the type of c.LastName. It could well be that all you need is:
select new {
Name = g.Key,
OpenBalance = g.Sum(t1 => t1.Credit)
}
... but if you need to get at any other aspects of c, you'll need to change your grouping expression.

LINQ count query returns a 1 instead of a 0

I have the following view:-
CREATE VIEW tbl_adjudicator_result_view
AS
SELECT a.adjudicator_id, sar.section_adjudicator_role_id, s.section_id, sdr.section_dance_role_id, d.dance_id, c.contact_id,
ro.round_id, r.result_id, c.title, c.first_name, c.last_name, d.name, r.value, ro.type
FROM tbl_adjudicator a
INNER JOIN tbl_section_adjudicator_role sar on sar.section_adjudicator_role2adjudicator = a.adjudicator_id
INNER JOIN tbl_section s on sar.section_adjudicator_role2section = s.section_id
INNER JOIN tbl_section_dance_role sdr on sdr.section_dance_role2section = s.section_id
INNER JOIN tbl_dance d on sdr.section_dance_role2dance = d.dance_id
INNER JOIN tbl_contact c on a.adjudicator2contact = c.contact_id
INNER JOIN tbl_round ro on ro.round2section = s.section_id
LEFT OUTER JOIN tbl_result r on r.result2adjudicator = a.adjudicator_id AND r.result2dance = d.dance_id
When I run the following query directly against the db I get 0 in the count column where there is no result
select adjudicator_id, first_name, COUNT(result_id)
from tbl_adjudicator_result_view arv
where arv.round_id = 16
group by adjudicator_id, first_name
However when I use LINQ query I always get 1 in the Count Column
var query = from arv in db.AdjudicatorResultViews
where arv.round_id == id
group arv by new { arv.adjudicator_id, arv.first_name} into grp
select new AdjudicatorResultViewGroupedByDance
{
AdjudicatorId = grp.Key.adjudicator_id,
FirstName = grp.Key.first_name,
Count = grp.Select(p => p.result_id).Distinct().Count()
};
What do I need to change in the View / Linq query.
You're not doing the same thing in the LINQ query as in the SQL. COUNT(result_id) does not count distinct values of result_id - it counts non-null values.
Try this instead:
Count = grp.Select(p => p.result_id).Where(x => x != null).Count()
The point is: you're grouping your data in the LINQ query - and you'll always get at least one group.
That group's Count may be 0 - but the count of groups will be 1.

Resources