How To Convert Sql Query to Linq Which contans Subquery - c#

My Query as Follows
`Select * from daps_user_activity where Userid In (Select Userid from daps_portaluser where EMR_ID = 24855) `
What is the equivalent query in linq please help me...

Try this, it's better that you use a join in this instance, instead of a sub-query:
var results = (from a in daps_user_activity
join u in daps_portaluser on a.Userid equals u.Userid
where u.EMR_ID == 24855
select a).ToList()

Alternatively, you could use this:
var results = (from a in daps_user_activity
from u in daps_portaluser
where u.EMR_ID == 24855
&& a.Userid == u.Userid
select a).ToList()
To me, it shows more clearly the main query and the subquery.
Credit goes to #Bruno Brant at Convert SQL Query (with Correlated Subquery) to LINQ in C#

Related

Linq to SQL Query with fk

I try to realize this query from T-SQL in Linq to SQL:
Select * from RPG r
join RPGPlayer e on r.RPGID = e.RPGID
join [User] i on e.UserID = i.UserID
where i.Username like '%Dunkel%'
The result is correct for 2 Rows on SQL-Query itself.
I try this:
rpgList.Where(y => y.RPGPlayers == y.RPGPlayers.Where(e => e.User.Username.Contains(player))).ToList();
(rpgList is a list of the complete table loaded before)
Not entirely sure regarding the question, but the following is my attempt to represent the SQL join statement in LINQ …
from r in RPG
join e in RPGPlayer on r.RPGID equals e.RPGID
join i in User on e.UserID equals i.UserID
where i.Username.Contains("Dunkel")

How to use 'In' SQL keyword in Entity Framework?

This is my SQL command
SELECT KEY,NAME
from COMPANY c
WHERE KEY IN (select KEY from USER_COMPANY where UserId = #UserId)
order by NAME asc
So I want to convert it to Entity Framework.
I try like this
var userCompany = (from u in db.USER_COMPANY
where u.UserId == UserId
select(u.KEY));
var user = (from c in db.COMPANY
where (c => userCompany.Contains(c.KEY)
select c);
but it is not working.
How to use the SQL IN keyword in Entity Framework?
Try this:
var query = from c in db.COMPANY
where (from u in db.USER_COMPANY
where u.UserId == UserId
select u.KEY).Contains(c.KEY)
orderby c.NAME
select c.KEY, c.NAME;
Note that this SQL query has the exact same meaning:
SELECT c.KEY, c.NAME
FROM COMPANY c
JOIN (SELECT DISTINCT KEY FROM USER_COMPANY where UserId = #UserId) u
ON U.KEY = C.KEY
ORDER BY c.NAME asc
So you should be able to just do:
var userCompany = (from u in db.USER_COMPANY
where u.UserId == UserId
select(u.KEY)).Distinct();
var result = from c in db.COMPANY
join u in userCompany
on c.KEY = u.KEY
select new {c.KEY, c.NAME};
My understanding is that the translation from .Contains() to IN is only just being added to EF6.
According to this work item (http://entityframework.codeplex.com/workitem/245) and the release note: Improved performance of Enumerable.Contains in LINQ queries.
So look for it in EF6

Linq's Column In (Select ...) Statement

How do you write a linq statement that does the equivalent of this subselect in MS SQL:
... WHERE
tblXref.Organization_Id IN (SELECT Organization_Id
FROM AppUser au INNER JOIN [User] u ON au.User_Id = u.Id
WHERE u.Username = usernameVariable)
Well, it's probably simpler to write the inner query separately (remembering that you're not executing the query):
var innerQuery = from au in db.AppUsers
join u in db.Users on au.User_Id equals u.Id
where u.UserName == userNameVariable
select au.Organization_Id;
var query = from tblXref in db.CrossReferences // or whatever
where innerQuery.Contains(tblXref.Organization_Id)
...;

LEFT LINQ TO SQL C# JOIN on many to many table

Hi im kinda new to linq to sql I know about the basics. The problem is I want to do a left join in a query. There are 3 tables in the query.
Claimants ( all rows should be returned from this table)
Claim
User
The query should return all Users who have Claimants. This is done through the many to many table Claim. But regardless of Users all Claimants should be returned. Thus the left join on Claimants.
I have the following query
var d = (from Claimants in DB.Claimants
join Claims in DB.Claims on Claimants.Claiment_ID equals Claims.Claiment_ID
join Users in DB.Users on Claims.User_ID equals Users.User_ID
where (Claimants.TrialDate.Value >= dtDayStart & Claimants.TrialDate <= dtDayEnd)
select new
{
ClaimantFirstName = Claimants.FirstName,
ClaimantLasname = Claimants.LastName,
ClaimantsID = Claimants.IDNumber,
Claimants.OurReference,
Claimants.TrialDate,
InterviewStart = Claims.DateTimeStart,
InterviewEnd = Claims.DateTimeEnd,
Claims.Priority,
UserFirstname = Users.FirstName,
UserLastName = Users.LastName,
UserID = Users.IDNumber
});
I have tried using an into statement as follows but with no luck
var d = (from Claimants in DB.Claimants
join Claims in DB.Claims on Claimants.Claiment_ID equals Claims.Claiment_ID
into TheClaimants
from Claims in TheClaimants.DefaultIfEmpty()
join Users in DB.Users on Claims.User_ID equals Users.User_ID
where (Claimants.TrialDate.Value >= dtDayStart & Claimants.TrialDate <= dtDayEnd)
select new
{
ClaimantFirstName = Claimants.FirstName,
ClaimantLasname = Claimants.LastName,
ClaimantsID = Claimants.IDNumber,
Claimants.OurReference,
Claimants.TrialDate,
InterviewStart = Claims.DateTimeStart,
InterviewEnd = Claims.DateTimeEnd,
Claims.Priority,
UserFirstname = Users.FirstName,
UserLastName = Users.LastName,
UserID = Users.IDNumber
});
I would appreciate it if someone could point me in the right direction as to how to use these joins left right correctly and explain how the work. Thank you very much in advance.
var d = (from Claimants in DB.Claimants
join Claims in DB.Claims on Claimants.Claiment_ID equals Claims.Claiment_ID)
.DefaultIfEmpty()
join Users in DB.Users on Claims.User_ID equals Users.User_ID
where (Claimants.TrialDate.Value >= dtDayStart & Claimants.TrialDate <= dtDayEnd)
.DefaultIfEmpty()
select new
{
ClaimantFirstName = Claimants.FirstName,
ClaimantLasname = Claimants.LastName,
ClaimantsID = Claimants.IDNumber,
Claimants.OurReference,
Claimants.TrialDate,
InterviewStart = Claims.DateTimeStart,
InterviewEnd = Claims.DateTimeEnd,
Claims.Priority,
UserFirstname = Users.FirstName,
UserLastName = Users.LastName,
UserID = Users.IDNumber
});
Left outter join
You must know a Luan. If you want all the Claiments to return start by selecting from Claiments and then left join onto the other tables.
Try the following :
LINQ to SQL Left Outer Join
In LINQ, the ".Join()" extension method is the equivalent of SQL inner join.
For outer joins you have to use the ".GroupJoin()" extension method.
Assuming you know the .Join well, the GroupJoin is simple to use. I have to admit that when I first needed to do an outer join in LINQ it was damn hard to find out. I cannot fanthom why did they call it like that.
Although in VB.Net, here's an article that presents various SQL constructs translated into LINQ syntax, even if in VB, still easy to convert to extension methods: http://blogs.msdn.com/b/vbteam/archive/2007/12/31/converting-sql-to-linq-part-6-joins-bill-horst.aspx?Redirected=true
EDIT: #DavidB posted in his comments a much better solution, but only if you can use some ORM navigational properties. If you don't have them, then GroupJoin is probably the most reasonable

linq to sql Distinct and orderby

var result = table1.Join(table2, o => o.ProgramID, t => t.ProgramID, (o, t) => new { o.ProgramID, t.Program })
.OrderBy(t => t.Program)
.Distinct();
the above linq statement actually returns the correct result, but he sql generated (below) is not as simple as it could be
SELECT [t2].[ProgramID], [t2].[Program]
FROM (
SELECT DISTINCT [t0].[ProgramID], [t1].[Program]
FROM [table1] AS [t0]
INNER JOIN [table2] AS [t1] ON [t0].[ProgramID] = [t1].[ProgramID]
) AS [t2]
ORDER BY [t2].[Program]
I would have thought the sql below is far cleaner but I'm not sure of the linq statement to achieve it.
select distinct
o.ProgramID,
t.Program
from
table1 0
inner join table2 t on t.ProgramID = o.ProgramID
order by t.Program
Thanks in advance
I don't know if it will help, but you can try something like this;
var result = (from o in table1
join t in table2 on o.ProgramID equals t.ProgramID
orderby t.Program
select new { o.ProgramID, t.Program }).Distinct();
I tried this and that works:
var result = (from o in table1
join t in table2 on o.ProgramID equals t.ProgramID
select new { o.ProgramID, t.Program })
.Distinct().OrderBy(t => t.Program)
.ThenBy(t => t.ProgramName)
.ThenBy(t => t.Description);
First you do Distinct and then OrderBy, then OrderBy works.
Profile the two queries, comparing stats-IO and the actual execution plan. It is entirely possible that it makes zero difference to the SQL server.
If you really want known TSQL, use ExecuteQuery-of-T and pass in the TSQL yourself. Maybe include some lock hints too (most commonly: NOLOCK)

Categories

Resources