LINQ count query returns a 1 instead of a 0 - linq

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.

Related

Linq how to join tables with a where clause on each table and a count

The following LINQ query isn't allowed when I use multiple where elements - it stops liking the 'into':
var query =
from ph in _db.PlayHits
join ua in _db.UserAgents on ph.UserAgentId equals ua.UserAgentId
where (ph.VideoId == 1 && ua.AgentString.Contains("test"))
into hits
select new
{
ResultCount = hits.Count()
};
Any idea why or how I amend this?
The equivilent sql I want is:
select count(*) as ResultCount
from Playhits ph
join UserAgents ua on ph.UserAgentId = ua.UserAgentId
where ph.VideoId = 1
and ua.AgentString like '%test%'
To my understanding, counting of the results can be done using the extension methond Count as follows.
var query =
from ph in _db.PlayHits
join ua in _db.UserAgents on ph.UserAgentId equals ua.UserAgentId
where (ph.VideoId == 1 && ua.AgentString.Contains("test"));
int Result = query.Count();

LINQ - count from select with join with no group by

Linq is brand new to me so I apologize if this is really stupid.
I am trying to get the count from a multi-table join with where clause, without group by. I've seen examples of group by and will resort to that if need be, but I am wondering if there is a way to avoid it. Is sql my query would look something like this;
SELECT Count(*)
FROM plans p
JOIN organizations o
ON p.org_id = o.org_id
AND o.deleted IS NULL
JOIN orgdata od
ON od.org_id = o.org_id
AND od.active = 1
JOIN orgsys os
ON os.sys_id = od.sys_id
AND os.deleted IS NULL
WHERE p.deleted IS NULL
AND os.name NOT IN ( 'xxxx', 'yyyy', 'zzzz' )
What's the best way to get this?
All you need is to call Count(). You're only counting the number of results. So something like:
var names = new[] { "xxxx", "yyyy", "zzzz" };
var query = from plan in db.Plans
where plan.Deleted == null
join organization in db.Organizations
on plan.OrganizationId equals organization.OrganizationId
where organization.Deleted == null
join orgData in db.OrganizationData
on organization.OrganizationId equals orgData.OrganizationId
where orgData.Active == 1
join os on db.OrganizationSystems
on orgData.SystemId equals os.SystemId
where os.Deleted == null &&
!names.Contains(os.Name)
select 1; // It doesn't matter what you select here
var count = query.Count();

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

Linq Nested Inner Joins

I want to join the following Tables
1. B_Book[1st Table]
-B_BID (Book ID)(PK)
-B_Name
-B_CategroyID (FK)
2. BI_BookInstance [2nd Table]
-BI_IID(Instance ID)
-BI_BID (FK)
-BI_Price
3. BC_BookCategory [3rd Table]
-BC_CategoryID (PK)
-BC_CategoryName
First Join B_Book and BI_BookInstance then join the result of those both with BookCategory.
(1st join)[B_BID equals BI_BID]
(2nd nested join)[result of 1st join B_CategoryID equals BC_CategoryID]
Edit
SQL would be something like the following:
SELECT * FROM
(SELECT * FROM B_Book b JOIN BI_BookInstance bi on b.B_BID = bi.BI_BID) as t1
JOIN BC_BookCategoryID bc on bc.BC_CategoryID = t1.B_CategoryID
What matches your query in LINQ would be the following (and you'll notice the similarity with SQL). I've also included some examples on how to rename the fields returned, such as Price or CategoryName:
var results = from b in B_Book
join bi in BI_BookInstance
on b.B_BID equals bi.BI_BID
join bc in BC_BookCategory
on b.B_CategoryID equals bc.BC_CategoryID
select new
{
// put in whatever fields you want returned here:
b.B_BID,
b.B_CategoryID,
b.B_Name,
bi.BI_BID,
bi.BI_IID,
Price = bi.BI_Price,
bc.BC_CategoryID,
CategoryName = bc.BC_CategoryName
};
I have supposed inner joins (your FKs is not null), so i would like query like this:
var ctx = new YourEntities();
var query = from b in ctx.B_Book
from bi in ctx.BI_BookInstance
from bc in ctx.BC_BookCategory
where b.B_BID == bi.BI_BID && b.B_CategoryID == bc.BC_CategoryID
select new
{
BInstID = bi.BI_IID,
BName = b.B_Name,
BPrice = bi.BI_Price,
BCategory = bc.BC_CategoryName
};
foreach (var item in query)
{
Console.WriteLine(item.BInstID);
Console.WriteLine(item.BName);
Console.WriteLine(item.BPrice);
Console.WriteLine(item.BCategory);
Console.WriteLine("");
}
You can do this without explicitly using linq's join statement, provided that navigation properties are in place:
from b in ctx.B_Book
from bi in b.BookInstances
select new { b.Property1, bi.Property2, b.BookCategory.Name }

many to many relationship

I am trying to write a linq to get data from many to many tables.
Here are the tables
Products (ID,Name,Description)
Products_Items (ID,ProductID,Description)
ProductsNeeds (ID,Name)
ProductsItems_Needs (ItemID,NeedsID)
This is the t-sql query
select gPro.Name,gProItems.ShortDescription,gProItems.Description,gNeeds.Name
from Products gPro
join Products_Items gProItems on gPro.ID = gProItems.ProductID
join ProductsItems_Needs gProNeeds on gProNeeds.ItemID = gProItems.ID
join ProductsNeeds gNeeds on gNeeds.ID = gProNeeds.NeedsID
where gProItems.ID = 1
this is the linq
var q = from p in objM.Products
join gpItems in objM.Products_Items on p.ID equals gpItems.ProductID
from needs in gpItems.ProductsNeeds
where gpItems.ID == 1
select p;
This query returns (Products) and it has the Produts_Items but it has not the ProductsNeeds.
What modifications should I do in order each Products_items to have the ProductsNeeds?
Thanks
Finally I found the solution.
The change was that instead of returning Products it returns Product_Items.
var q = from pItems in objM.Products_Items
join p in objM.Products on pItems.ID equals p.ID into joinedProducts
from p in joinedProducts.DefaultIfEmpty()
from needs in pItems.ProductsNeeds
where pItems.ID == 1
select pItems;

Resources