Use subquery in linq query - c#

How can I construct the below sql query in linq query to get the results ?
SELECT PageNumber from LMS_SurveyQuestion WHERE SurveyQuestionID IN
(SELECT SurveyQuestionID from LMS_SurveyQuestionOptionChoice
WHERE NextPageNumber = 4) and SurveyID = 1

Have a look at this article. Basically, if you want to implement SQL IN query in LINQ, you need to construct an inner query first, and then use the Contains() method. Here's my attempt:
var innerQuery = (from log in LMS_SurveyQuestionOptionChoice where log.NextPageNumber = 4 select log.SurveyQuestionID);
var result = (from f in LMS_SurveyQuestion where innerQuery.Contains(f.SurveyQuestionID) && f.SurveyID = 1 select f);
Hope this will help.

try this
var result = from l in LMS_SurveyQuestion
let lsq = from l_S in LMS_SurveyQuestionOptionChoice
where l_S.NextPageNumber = 4
select l_S.SurveyQuestionID
where lsq.Contains(l.SurveyQuestionID) and l.surveyid = 1
select l.PageNumber;

Related

Linq query to get get count from multiple tables

I have a query wherein I need to get the count from 2 different tables. Here is a very simple form of the query (my query has more joins and conditions but this is the part I am stuck on):
select (select count(1) from Table1) as One, (select count(1) from Table2) as Two
The following linq queries works but I would like to do the above with a single linq query sent to the SQL Server. This query and many other versions I have tried, result in 2 queries sent to the server:
var query1 = from m in this.Table1 select m;
var query2 = from sr in this.Table2 select sr;
var final = new { One = query1.Count(), Two = query2.Count() };
I also tried this and this also sends 2 queries:
var final = from dummy in new List<int> { 1 }
join one in query1 on 1 equals 1 into ones
join two in query2 on 1 equals 1 into twos
select new { One = ones.Count(), Two = twos.Count()};
You need to make it a single LINQ query that can be translated:
var final = (from m in this.Table1.DefaultIfEmpty()
select new {
One = (from m in this.Table1 select m).Count(),
Two = (from sr in this.Table2 select sr).Count()
}).First();
Note that putting the sub-queries into an IQueryable variable will cause three separate queries to be sent.
Alternatively, since Count() doesn't have a query syntax equivalent, this is a little more compact in lambda syntax:
var final = this.Table1.DefaultIfEmpty().Select(t => new {
One = this.Table1.Count(),
Two = this.Table2.Count()
}).First();

How do I convert this tSQL statement to LINQ using group by in a sub query

I have the following MSSQL query I am trying to convert to LINQ. I am using entity framework with the following syntax to get at the data.
var rv = (from i in DC.TableA select i).ToList();
This is the sql I want to write a C# LINQ query for but I cannot figure it out. Can someone help?
select BTO.*
from TableA BTO
join
(
select eqnum, max(testdate) as testdate
from TableA BTO1
where
BTO1.eqnum in ('M0435', 'Z0843') and
BTO1.testdate <= '2008-06-01'
group by eqnum
) T1
on
T1.eqnum = BTO.eqnum and
T1.testdate = BTO.testdate
order by EqNum;
I think there is opportunity to rewrite your query, but for information purposes I rewrote your sql into linq verbatim.
If you explain what you are trying to achieve we can provide alternative sql / linq
var eqnums = new[] { "M0435", "Z0843" };
var testdate = "2008-06-01";
var query = from bto in DC.TableA
join t1 in (
from bto1 in DC.TableA
where eqnums.Contains(bto1.eqnum) &&
bto1.testdate.CompareTo(testdate) <= 0
group bto1 by bto1.eqnum into g
select new
{
eqnum = g.Key,
testdate = g.Max(x => x.testdate)
}
) on new { bto.eqnum, bto.testdate } equals new { t1.eqnum, t1.testdate }
orderby bto.eqnum
select bto;

LINQ TO SQL Subquery

I am learning LINQ to SQL. And I want to write a LINQ TO SQL Query for the following:
SELECT TOP 1 * From
(select Top 2 * from Data ORDER BY ID DESC)
ORDER BY ID
According to my understanding it is written something like this;
GridView1.DataSource = from ( from data in dbCon.Data ORDER BY data.ID DESC
select Top 2 *)ORDER BY data.ID
select TOP 1 * ;
but it is not correct. Can anybody tell me the correct syntax? and links that can help me learn LINQ TO SQL Syntax for writing subqueries?
This should work for you:-
var result = (from x in
((from data in db.DATA orderby data.ID descending select data).Take(2))
orderby x.ID
select x).FirstOrDefault();
Try this:
var query = (from x in db.Data
select x).OrderByDescending(x=> x.Id).Take(2);
var query2 = (from y in query
SELECT y).OrderByDescending(y=> y.Id).Take(1);

Joining tables NHibernate

I would like to write following query to an NHibernate-QUery in order to get a list of PRESC_DEL ordered by PRESC.ADMINDATE
select * from PRESC_DEL, PRESC
where PRESC.ID = PRESC_DEL.ID_PRESC
and PRESC_DEL = PRESC_DEL.ID_DISTRIBUTIE
or by PRESC.ADMINDATE
How do I make the join?
var query = (from pd in session.Query<PrescDel>()
where pd.??? = pd.IdDistribute
orderby pd.AdminDate
select pd);
var results = query.Fetch(x => x.Presc).ToList();

how to convert this T-SQL statment to linq

i'm starter in linq, i have write this T-SQL Query
select * from DOCUMENT_TYPES where document_id in(
select document_id from Clearance_Document where Clearance_id=(select clearance_id from clearance_id from request where request_id=3))
i want convert this T-SQL Query to linq, please help me, thanks
Well, I would start first by refactoring your SQL into something other than a chain of nested sub-queries. I think this ought to do the same thing, and it's much more readable:
SELECT
*
FROM
DOCUMENT_TYPES dt
JOIN
Clearance_Document cd
ON
dt.document_id = cd.document_id
JOIN
Request r
ON
cd.clearance_id = r.clearance_id
WHERE
r.request_id = 3
(I'm assuming that from clearance_id from request was a typo.)
Then you can easily refactor into a LINQ statement:
var result = from dt in DOCUMENT_TYPES
join cd in Clearance_Document on dt.document_id equals cd.document_id
join r in Request on cd.clearance_id equals r.clearance_id
where r.request_id = 3
select new {
property1 = dt.something,
property2 = cd.somethingElse,
...
};
var result =
from a in DOCUMENT_TYPES
let list =
(
from b in Clearance_Document
where b.Clearance_id == (from c in clearance_id where request_id == 3).First<string>())
select b
).ToList()
where list.Contains(a.document_id)
select a;
Something like that should do (i guessed you're using EF, but you can easyly adapt to other LinQ-Types):
context.Document_Types.Where(doc =>
conext.Clearance_Document.Where(cd =>
cd.Clearance_Id == context.Request.Single(r => r.Request_Id == 3)
).Contains(doc.Document_Id)
).ToList();
How about
var result = c.Id context.Request.Single(r => r.Id == 3)
.Clearances.SelectMany(c => x.DocumentTypes);
In effect, get the one and only Request with an Id equal to 3, then get all the DocumentTypes of all its Clearances.
If your database is set up with the appropriate foreign keys these relationships will be automatically generated as part of your model.

Categories