Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello experts, I have a series of codes in SQL Query format, in this code I joined 3 tables together.
here is my code:
select distinct(t.UserNO),t.UserName,s.TotalDays from User_Tbl as t 
join( select ChartNo from Chart_Rest_Tbl) as f ON t.UserNO = f.ChartNo join(select ChartNO, sum(Days) as TotalDays from Chart_Rest_Tbl
group by ChartNo) AS s ON f.ChartNO = s.ChartNo

Now I want to write the above code in C# format, like this code(I mean how to write above code in c# format,The code below is just an example and I have nothing to do with the code below):
var st = (from s in db.Worker_Tbl
   join o in db.User_Tbl on s.WorkerNO equals o.UserNO
   where o.UserNO == txtsearch1
   select new { s.WorderId, o.UserName, s.WorkerNO, s.GPEntireDate, s.GPExpiredDate, s.GPCount }).ToList();


What I have tried:

i don't know how to write
SUM(Days)
in C# format or how write
distinct

thank you for your time <3
Posted
Updated 14-Dec-23 8:12am
v4

Here is the LINQ format in C# from your SQL query.
C#
var query = from t in dbContext.User_Tbl
            join f in dbContext.Chart_Rest_Tbl.Select(x => x.ChartNo).Distinct() on t.UserNO equals f
            join s in dbContext.Chart_Rest_Tbl.GroupBy(x => x.ChartNo)
                                               .Select(g => new { ChartNO = g.Key, TotalDays = g.Sum(x => x.Days) })
            on f equals s.ChartNO
            select new
            {
                UserNO = t.UserNO,
                UserName = t.UserName,
                TotalDays = s.TotalDays
            };
var result = query.Distinct().ToList();
To modify or further reference, you can try the below tools to convert your SQL query to LINQ format in C#:
LINQPad - The .NET Programmer's Playground[^]
Home page - Linqer[^]
 
Share this answer
 
v2
Comments
Max Speed 2022 6-Jan-24 5:26am    
thanks bro <3
M Imran Ansari 7-Jan-24 12:55pm    
You're welcomed! Happy to assist. :)
Max Speed 2022 12-Jan-24 15:56pm    
hi bro,I want to add 4 more columns from the Chart_Rest_Tbl table to this query, these are my columns "TypeofRest,ID,Bdate,Result"
I tried a lot to add these columns to the query, but unfortunately, duplicate rows were joined together :( and also i wanna do this condition where f.Result == "Accept" && f.TypeofRest == "Es"
C#
string sql = @"
select distinct(t.UserNO),t.UserName,s.TotalDays from User_Tbl as t 
join( select ChartNo from Chart_Rest_Tbl) as f ON t.UserNO = f.ChartNo join(select ChartNO, sum(Days) as TotalDays from Chart_Rest_Tbl
group by ChartNo) AS s ON f.ChartNO = s.ChartNo
" ;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900