简体   繁体   中英

How to convert C# Linq to query in SQL Server?

I'm a junior developer and trying to convert the following linq statement to T-SQL:

var items = from u in DataContext.Users_SearchUsers(searchPara.UserFirstName,
                                                    searchPara.UserLastName,
                                                    searchPara.UserEmailAddress,
                                                    fetchOptions.page,
                                                    fetchOptions.rp,
                                                    fetchOptions.sortname,
                                                    fetchOptions.sortorder)
                                 .ToList()
            join a in DataContext.UserAccesses
                                 .Where(x => x.Access.AccessTypeId == 4).ToList() on u.UserID equals a.UserId into accessGroup
            select new {};

Can one please help me ? into accessGroup ---> (very important)

First of all you need to understand where your data is coming from. You are loading information from Users_SearchUsers on the one hand and UserAccesses on the other hand. The first query looks like

select <somecolumns>
from users
where <somefilters>;

(you need to use your actual columns and criteria, but Users_SearchUsers is not specified in the question at all). I have ignored paging here for the sake of simplicity

The second query looks like this:

select *
from user_accesses
where access_type_id = 4;

Let's join the two:

select <someoutercolumns>
from
(
select <someinnercolumns>
from users
where <somefilters>
) t1
join
(
select <someotherinnercolumns>
from user_accesses
where access_type_id = 4
) t2
on t1.user_id = t2.user_id;

These queries are probably not the exact solutions you need, but you want the answers to improve, then improve your question.

The requirement makes sense if the LINQ query is very slow. In that case you will need to refactor it in the following manner:

select <somecolumns>
from users
join user_accesses
on users.user_id = user_accesses.user_id and user_accesses.access_type_id = 4
where <somefilters>;

you can use this code

select *(you can put your columns instead *)
from Users
join UserAccesses
on Users.userid = UserAccesses.userid
where UserAccesses.typeid = 4;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM