SQL Subquery in LINQ for Entity Framework 4.0 - sql-server

I'm new to LINQ and EF, but I've been able to stumble through for the majority of the queries I have, but this one has me completely confused. No matter what I try, it comes up in SQL Profiler as a big mess :-).
I have two tables: Users and UsersProjects. The goal of this query is to list all the users who are working on projects with the specified user. Here is the query as I have it written in SQL. It's a subquery, but I don't know of a way to simplify it further, but I'm open to suggestions there as well.
SELECT DISTINCT Users.FirstName, Users.LastName
FROM Users INNER JOIN UsersProjects ON Users.ID=UsersProjects.UserID
WHERE UsersProjects.ProjectID IN
(SELECT ProjectID FROM UsersProjects WHERE UserID=#UserID)
Anybody able to help?? It seems like a fairly simple subquery in SQL, but in LINQ, I'm baffled.
Thanks,
Jorin

Something like this I guess:
from u in Users
from projectId in UsersProjects.Where(up => up.UserId == #userId).Select(p => p.ProjectId)
where u.UsersProjects.Any(up => projectId == up.ProjectId)
select u
or (it's your sql query in linq)
(from u in Users
join up in UsersProjects on #userId equals up.UserId
where u.UsersProjects.Any(up2 => up2.ProjectId == up.ProjectId)
select u).Distinct()

Related

I need to get the numbers of Users for each language

I have a list of languages and I need to show how many users subscribe to each.
I work on my project with Angular 13 and ASP.NET Core 6 and SQL Server but there are two blocked ways
Use Angular services in NgFor but return infinite loops and crash.
Use .NET to return the list of languages and loop a second query to get count users but not work.
The last is to create something with SQL Server (I don't know how)
[
In your API you will need to return a payload that you can use to show the results you expect. From the API layer, you need to access the database and transform data to the meet the former challenge. The query to obtain the results is rather straightforward.
SELECT
L.lang_id,
L.title,
L.description,
L.image,
COUNT(*) as UserCount
FROM
Languages L
INNER JOIN Users U on U._id_lang = L.id_lang
GROUP BY
L.id_lang
#ross bush thank you
SELECT
CAST(L.id_Lang AS NVARCHAR(200)) AS idLang ,
CAST(L.title AS NVARCHAR(200)) AS TitleLang ,
CAST(L.img AS NVARCHAR(200)) AS ImgLang ,
COUNT(*) AS UserCount
FROM
dbo.Languages L
INNER JOIN dbo.Users U on U.id_lang = L.id_Lang
GROUP BY
CAST(L.id_Lang AS NVARCHAR(200)) ,CAST(L.title AS NVARCHAR(200)) , CAST(L.img AS NVARCHAR(200))

SQL name instead of ID in many to many relation

I am trying to make simple chat with database. So I created 2 tables:
Users (ID(PK), Name, Password)
Messages (ID(PK), senderID(FK from users), recipientID(FK from users)), text
I am really noob in SQL and I just can't write query that will return table Messages but with normal names instead of senderID and recipientID. Also I didn't find examples where 1 table uses twice, so JOIN didn't work for me, or I used it in wrong way.
SELECT US.Name as SenderName, UR.Name as RecipientName, M.text
FROM Messages M JOIN Users US ON US.ID = M.senderID
JOIN Users UR ON UR.ID = M.recipientID
Not sure if I understand your question correctly, or which db you are using but this is what I think you are looking for:
SELECT Messages.text, Users.name
FROM Messages
inner JOIN Users
ON Messages.sender_id = Users.id

SQL Server : using SELECT in NOT IN WHERE Clause

I've been using this query statement ever since. I wonder why this does not work on SQL Server 2008 R2.
SELECT
UserName
FROM
Users
WHERE
UserName NOT IN (SELECT UserName FROM UserTableT2)
The codes does not return any data. Goal is select all UserName in Users table which do not belong to UserTableT2.
EDIT:
Here's the actual query
Update using #Tim Schelmter's query:
Update :
Update:
Thank you!
I would use NOT EXISTS:
SELECT u.UserName
FROM Users u
WHERE NOT EXISTS
(
SELECT 1 FROM UserTableT2 ut2
WHERE u.UserName = ut2.UserName
)
Why? Because it works also if there are NULL values in UserTableT2.UserName.
Worth reading:
Instead of NOT IN, use a correlated NOT EXISTS for this query pattern.
Always. Other methods may rival it in terms of performance, when all
other variables are the same, but all of the other methods introduce
either performance problems or other challenges.
With your updated columns and tables:
SELECT u.usr_id
FROM ousr u
WHERE NOT EXISTS
(
SELECT 1 FROM ApprovalStageApprovers asa
WHERE u.usr_id = asa.ApprovalUser
)

Relationships between stored procs?

I'll start by saying hello! This forum has been a great help to me over the past few months, but have only now joined and asking my first question.
I'm working with the Northwind database in SQL Server 2008 r2 to build a vb.net application. I've been wrecking my head for a week trying to figure out how to make an order/invoice form. I can get the information I need to display using separate stored procs (GetCustInfo, GetOrderInfo, GetProductInfo, or something like that), but I'm having trouble figuring out how to display them on the form.
When I select all the info I need in one sp (as in the Invoice view which comes built in the db), I get 2155 rows, which is the number of items which have been ordered in the company history.
What I want to do is display this information, but navigate by OrderID (which would give me 830 rows, each with a certain number of products related to the OrderID). So I'm thinking I need different stored procs related which can be related in some way.
I'd really appreciate any help that can be given on this.
Many thanks in advance.
p.s. I have screenshots of the Northwind sample app which shipped/ships with Access, which is really what I'm trying to recreate in SQL Server. Unfortunately, no code!
MM
Yes you can achieve it by many ways and SP is one. Just create a SP to select that related products passing OrderId as a input parameter.
Some options (with contrived examples):
You can ALTER existing stored procedures to get what you want (not recommended if you want to use the existing procedures for other queries).
ALTER PROCEDURE usp_ExistingProcedure
AS
BEGIN
SELECT t1.Value
, t2.Value
-- Supose that this was the addition we made to an existing stored procedure
, t2.ValueTwo
FROM TableOne t1
INNER JOIN TableTwo t2 ON t1.ID = t2.ID
END
You can CREATE new stored procedures for your queries; in the above example, it would be a create procedure with a new name.
You may be able to create a VIEW to obtain what you need - this will operate a little differently.
CREATE VIEW uv_ApplicationView
AS
SELECT t1.Value
, t2.Value
, t2.ValueTwo
FROM TableOne t1
INNER JOIN TableTwo t2 ON t1.ID = t2.ID
You can pull the query directly from the VB application, though if you want to reuse it for something else, I wouldn't recommend this approach.
// A re-usable approach calling a stored procedure
SqlCommand myQuery = new SqlCommand("EXECUTE usp_myQuery", sqlConn);
// A query directly in the C# code:
string msQuery = "SELECT t1.Value, t2.Value, t2.ValueTwo FROM TableOne t1 INNER JOIN TableTwo t2 ON t1.ID = t2.ID"
// Later ...
SqlCommand myQuery = new SqlCommand(msQuery, sqlConn);

How would I write this query with DBIX::Class?

I've seen a few other questions on Stackoverflow that discuss sub-selects, but they usually relate to the use of multiple tables. In most cases, a proper join could serve the same purpose.
However my query below refers to a single table. How would I write this using DBIX::Class?
select ID, username, email, role
from Employees
where (ID in
(select max(ID)
from Employees
where username = 'jsmith'
))
order by ID DESC
Thanks!
--
Edit 1: SQL code fix
The Cookbook has almost the exact same query as example.
Your SQL query doesn't make sense to me because the subquery returns a single id, so WHERE id = () would make more sense.
What are you trying to accomplish with it?

Resources