Entity Framework Linq Query of 3 tables - entity-framework

I have this 3 table query that doesn't return any results. Does anybody have any suggestions on what I am doing wrong? _id is a global variable.
'If there is a guest list then display each person in it
Dim guests = (From g In myEntities.GuestLists
From p In myEntities.Pictures
From u In myEntities.UserProfiles
Where g.EventID = _id
Where p.UserID = g.GuestID
Where u.UserID = g.GuestID
Select New With {p.ImUrl, u.FirstName, u.LastName, u.UserID}).SingleOrDefault()
Repeater1.DataSource = guests
Repeater1.DataBind()
This syntax works for a single table or two table query so I assumed 3 tables would be the same.

I think you have to JOIN the tables.
Like this (untested!)
From g In myEntities.GuestLists
Join p In myEntities.Pictures On g.GuestID Equals p.UserID
Join u In myEntities.UserProfiles On g.GuestID Equals u.UserID
Where g.EventID == _id
Select New With {p.ImUrl, u.FirstName, u.LastName, u.UserID}

Related

How to add a where clause to an EF query which has a grouping

I'm trying to find the number of bookings each user has made. This code works great - it does a join onto bookings and groups them and then does a count.
var bookingsByUser = from u in _repo.Users()
join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
into g
select new { UserId = u.UserId, TotalBookings = g.Count() };
However, I now want to exclude a certain restaurant, so I try to add a where clause:
var bookingsByUser = from u in _repo.Users()
join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
where b.RestaurantId != 21
into g
select new { UserId = u.UserId, TotalBookings = g.Count() };
However now I get an error "A query body must end with a select clause or a group clause". I can't seem to use "where" on the join table to filter the records before grouping. Is there a better way to do this?
Try this:
var bookingsByUser = from u in _repo.Users()
join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
where b.RestaurantId != 21
group b by u.UserId into sub
select new {
UserId = sub.Key,
TotalBookings = sub.Count()
};

Is this Correlated SubQuery Correct

I am trying to wrap my head around sub-queries (correlated). Although the book explains (MS SQL Server 2012) it I'm still a little confused. Using three tables, Orders, Products and OrderDetails I want to find the sum of all products that were shipped to USA. I came up with the following query but do not quite understand how I got there except the correlation is referencing the 'where' in the outer query. Can someone correct my work and offer better explanation than book?
SELECT p.productid, p.productname, SUM(qty * od.unitprice) AS TotalAmount
FROM Production.Products AS p
JOIN Sales.OrderDetails AS od
ON p.productid = od.productid
WHERE N'USA' IN
(SELECT o.shipcountry
FROM Sales.Orders AS o
JOIN Sales.OrderDetails AS od
ON o.orderid = od.orderid
WHERE shipcountry = N'USA')
GROUP BY p.productid, p.productname;
SELECT
p.ProductID
, p.ProductName
, SUM(qty * od.UnitPrice) as [Total_Amount]
FROM
Production.Products productid
JOIN Sales.OrderDetails as od on p.productid = od.product
JOIN SalesOrders as o on o.OrderID = od.OrderID
WHERE
o.Shipcountry in ('USA')
Group BY
p.ProductID,
P.ProductName
The following should work - you technically dont require the sub query. Will only bog down the query.

TSQL efficiency - INNER JOIN replaced by EXISTS

Can the following be rewritten to be more efficient?
I would use EXISTS if I didn't need fields from country but I do need those fields, and am not sure how to write this to make it more efficient.
SELECT distinct
p.ProvinceID,
p.Abbv as RegionCode,
p.name as RegionName,
cn.Code as CountryCode,
cn.Name as CountryName
FROM dbo.provinces AS p
INNER JOIN dbo.Countries AS cn ON p.CountryID = cn.CountryID
INNER JOIN dbo.Cities c on c.ProvinceID = p.ProvinceID
INNER JOIN dbo.Listings AS l ON l.CityID = c.CityID
WHERE l.IsActive = 1 AND l.IsApproved = 1
There are two things to note:
You're joining to dbo.Listings which results in many records, so you need to use DISTINCT (usually an expensive operator)
For any tables with columns not in the select you can move into an EXISTS (but the query planner effectively does this for you anyway)
So try this:
SELECT
p.ProvinceID,
p.Abbv as RegionCode,
p.name as RegionName,
cn.Code as CountryCode,
cn.Name as CountryName
FROM dbo.provinces AS p
INNER JOIN
dbo.Countries AS cn
ON p.CountryID = cn.CountryID
WHERE EXISTS (SELECT 1 FROM
dbo.Listings l
INNER JOIN dbo.Cities c
on l.CityID = c.CityID
WHERE c.ProvinceID = p.ProvinceID
AND l.IsActive = 1 AND l.IsApproved = 1
)
Check the query plans before and after - the query planner might be smart enough to do this anyway, but you have removed your distinct
The following will often perform even better by providing the optimizer more useful information:
SELECT
p.ProvinceID,
p.Abbv as RegionCode,
p.name as RegionName,
cn.Code as CountryCode,
cn.Name as CountryName
FROM dbo.provinces AS p
INNER JOIN
dbo.Countries AS cn
ON p.CountryID = cn.CountryID
INNER JOIN (
SELECT
p.ProvinceID
FROM
dbo.Listings l
INNER JOIN dbo.Cities c
on l.CityID = c.CityID
WHERE l.IsActive = 1 AND l.IsApproved = 1
GROUP BY
p.ProvinceID
) list
on list.ProvinceID = p.ProvinceID

Get Greatest date across multiple columns with entity framework

I have three entities: Group, Activity, and Comment. Each entity is represented in the db as a table. A Group has many Activities, and an Activity has many comments. Each entity has a CreatedDate field. I need to query for all groups + the CreatedDate of the most recent entity created on that Group's object graph.
I've constructed a sql query that gives me what I need, but I'm not sure how to do this in entity framework. Specifically this line: (SELECT MAX(X)
FROM (VALUES (g.CreatedDate), (a.CreatedDate), (c.CreatedDate)) Thanks in advance for your help. Here's the full query:
WITH GroupWithLastActivityDate AS (
SELECT DISTINCT
g.Id
,g.GroupName
,g.GroupDescription
,g.CreatedDate
,g.ApartmentComplexId
,(SELECT MAX(X)
FROM (VALUES (g.CreatedDate), (a.CreatedDate), (c.CreatedDate)) AS AllDates(X)) AS LastActivityDate
FROM Groups g
LEFT OUTER JOIN Activities a
on g.Id = a.GroupId
LEFT OUTER JOIN Comments c
on a.Id = c.ActivityId
WHERE g.IsActive = 1
)
SELECT
GroupId = g.Id
,g.GroupName
,g.GroupDescription
,g.ApartmentComplexId
,NumberOfActivities = COUNT(DISTINCT a.Id)
,g.CreatedDate
,LastActivityDate = Max(g.LastActivityDate)
FROM GroupWithLastActivityDate g
INNER JOIN Activities a
on g.Id = a.GroupId
WHERE a.IsActive = 1
GROUP BY g.Id
,g.GroupName
,g.GroupDescription
,g.CreatedDate
,g.ApartmentComplexId
I should add that for now I've constructed a view with this query (plus some other stuff) which I'm querying with a SqlQuery.

Entity SQL selecting from more then 3 tables

I am new to Entity framwork and currently trying hard to get used this programming paradigm. I have this query which i want to write in Entity SQL.
SELECT f.id, f.personName, c.Category, j.busCode, s.description, f.StartDate, (SELECT COUNT(*) FROM Analysis WHERE id = f.id) As numOfAnalysis
FROM forms f
INNER JOIN Jobs j ON f.id = j.id
INNER JOIN category c ON j.categoryid = c.categoryid
INNER JOIN stage s ON f.stageid = s.stageid
WHERE j.busCode NOT IN ('xyz', 'YYY')
ORDER BY startDate
I can get records from two tables but as soon as i add third table using the navigation property, i get error table category is not loaded in the current context. I am using .net 3.5. Keep in mind that EDM V2 doest not have foreign keys and i think the only way to traverse through the table relationship is navigation property.
Any help will be deeply appreciated.
Thanks
Coder74
If you use should be able to mount this Linq query.
I tried to put together, but in the rush and no such test is complicated.
You can use this reference as support: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
var result = (from f in forms
join j in Jobs on f.id equals j.id
join c in Category on j.categoryid equals c.categoryid
join s in stage on f.stageid equals s.stageid
join a in Analysis on a.id equals f.id
where !(new int[] { 'xyz', 'YYY' }).Contains(j.busCode)
orderby f.StartDate
select {
id =f.id,
personName = f.personName,
Category = c.Category,
busCode = j.busCode,
description = s.description,
StartDate = f.StartDate,
numOfAnalysis = a.Count()
}).ToList()
Julio Spader
W&S Soluções de Internet