Convert linq to SQL - c#

Does anyone know how to translate this? When I hit the debugger I get 3 different queries and var contains an array of results. I am trying to replace that line with a method that will call a stored procedure but I do not understand what the query should be. Thanks a lot
var restbl =
context.tbl_one.FirstOrDefault(d => d.qty < d.tbl_two.Count(a => !a.tbl_three.ust))
?? context.tbl_one.FirstOrDefault(d => d.qty > d.tbl_two.Count(a => !a.tbl_three.ust));
{SELECT
`Extent1`.`id`,
`Extent1`.`name`,
`Extent1`.`qty`,
`Extent1`.`cdate`
FROM `tbl_one` AS `Extent1`}
{SELECT
`Extent1`.`id`,
`Extent1`.`tbl_one_id`,
`Extent1`.`tbl_three_id`,
`Extent1`.`enabled`
FROM `tbl_two` AS `Extent1`}
{SELECT
`Extent1`.`id`,
`Extent1`.`ttid`,
`Extent1`.`code`,
`Extent1`.`cdate`,
`Extent1`.`mdate`,
`Extent1`.`prt`,
`Extent1`.`ust`
FROM `tbl_three` AS `Extent1`}
var countToAdd = restbl.qty - context.tbl_two.Count(a => a.tbl_one_id == restbl.id && !a.tbl_three.ust);

You can use LINQPad or Linquer tool for easily converting your linq query to SQL or vice versa. They are very helpful in converting complex queries.

My assumption would be: (assuming you use MSSQL)
result= SELECT TOP 1 FROM tbl_one t1 WHERE t1.qty< (SELECT COUNT(*) FROM tbl_two t2 INNER JOIN tbl_three t3 ON t3.id=t2.tbl_three_id WHERE t3.ust = 0 AND t1.id=t2.tbl_one-id)
if (result IS NULL)
result= SELECT TOP 1 FROM tbl_one t1 WHERE t1.qty> (SELECT COUNT(*) FROM tbl_two t2 INNER JOIN tbl_three t3 ON t3.id=t2.tbl_three_id WHERE t3.ust = 0 AND t1.id=t2.tbl_one-id)

Related

Change sql query to linq in mvc

I want to change sql query to linq using join statement. The query should retrieve columns (days and startdate) while matching records of table 1 to table. In short converting sql query to linq using join statement.
Below is what i've tried.
SQL Query (Working)
SELECT *
FROM dbo."Batches"
INNER JOIN dbo.StudentBatchRelation
on dbo.Batches.Id = dbo.StudentBatchRelation.BatchId
WHERE
dbo.StudentBatchRelation.StudentId = '3d980306-e36e-4581-8c98-219717cb1668'
LINQ (not fetching result)
var result = (from t1 in contBatch.GetallBatchList()
join t2 in contStudent.getAllStudentBatchList()
on t1.Id equals t2.batchId where t2.studentId == studentid
select new { t1.Days, t1.BatchDate }).ToList();
If your EF entities are well defined, you could simplify your query with :
var result = Db.Batches
.Include(p => p.StudentBatchRelation)
.Where(p => p.StudentBatchRelation.StudentId = "3d980306-e36e-4581-8c98-219717cb1668")
.ToList();
Otherwise, if you have to use your Getallxxxx functions, you could do :
var result = (from t1 in contBatch.GetallBatchList()
join t2 in contStudent.getAllStudentBatchList()
on t1.Id equals t2.batchId
where t2.studentId == "3d980306-e36e-4581-8c98-219717cb1668"
select t1)
.ToList();

SQL to LINQ - left join from same table using values equal to and greater than

I have the following SQL query which I am trying to convert to LINQ.
SELECT t1.*
FROM table1 t1
LEFT JOIN table1 t2
ON (t1.MusicId = t2.MusicId AND t1.MusicDetailId > t2.MusicDetailId)
WHERE t2.MusicDetailId IS NULL and t1.SingerId = 2
ORDER BY t1.MusicId
I have tried the following but I am not getting the correct data back.
var query =
from t1 in table1
from t2 in table1
where t1.MusicId == t2.MusicId && t1.MusicDetailId > t2.MusicDetailId
where t1.SingerId == 2 && t2.MusicDetailId == null
orderby t1.MusicId
select t1;
Is anyone able to help to get this SQL query converted to LINQ correctly?
var query = from t1 in table1.Where(X=> X.SingerId == 2)
join t2 in table1.Where(X=>X.MusicDetailId ==null) on t1.MusicId equals t2.MusicId
where t1.MusicDetailId > t2.MusicDetailId
select t1 ;

Using Linq to Entities and havign a NOT IN clause

I have a SQL query that I am trying to convert to LINQ:
SELECT * FROM TABLE1
WHERE LICENSE_RTK NOT IN(
SELECT KEY_VALUE FROM TABLE2
WHERE REFERENCE_RTK = 'FOO')
So I wrote one query for inner query and then one query for the outer one and used Except:
var insideQuery = (from pkcr in this.Repository.Context.TABLE2 where pkcr.Reference_RTK == "FOO" select pkcr.Key_Value);
var outerQuery = (from pl in this.Repository.Context.TABLE1 select pl).Except(insideQuery);
But this is wrong. Cannot even compile it. What is the correct way of writing this?
You cannot compile second query, because Except should be used on Queryables of same type. But you are trying to apply it on Queryable<TABLE1> and Queryable<TypeOfTABLE2Key_Value>. Also I think you should use Contains here:
var keys = from pkcr in this.Repository.Context.TABLE2
where pkcr.Reference_RTK == "FOO"
select pkcr.Key_Value;
var query = from pl in this.Repository.Context.TABLE1
where !keys.Contains(pl.License_RTK)
select pl;
NOTE: Generated query will be NOT EXISTS instead of NOT IN, but that's what you want
SELECT * FROM FROM [dbo].[TABLE1] AS [Extent1]
WHERE NOT EXISTS
(SELECT 1 AS [C1]
FROM [dbo].[TABLE2] AS [Extent2]
WHERE ([Extent2].[Reference_RTK] == #p0) AND
([Extent2].[Key_Value] = [Extent1].[License_RTK]))

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)

LINQ to SQL and Self Related Table

We have the following test model in the dbml file:
Model http://www.freeimagehosting.net/uploads/a86582498a.gif
For the test case there are 4 records in the table, 1 parent, 3 children. We are looking for the siblings of a specific record, including the specific record.
using (var db = new TestDataContext())
{
var query =
from f in db.Foos
where f.Name == "Two"
select f.Foo1.Foos; // get the record's parent's children
var foos = query.SelectMany(f => f); // project the EntitySet
Assert.AreEqual(3, foos.Count()); // passes
}
This returns the correct items with the following SQL:
SELECT [t2].[FooId],
[t2].[ParentFooId],
[t2].[Name]
FROM [dbo].[Foos] AS [t0]
INNER JOIN [dbo].[Foos] AS [t1] ON [t1].[FooId] = [t0].[ParentFooId]
CROSS JOIN [dbo].[Foos] AS [t2]
WHERE ([t0].[Name] = #p0)
AND ([t2].[ParentFooId] = [t1].[FooId])
We are wondering about the CROSS JOIN, this apparently is the result of the SelectMany?
Is there another way we should approach this in order to not have the CROSS JOIN?
You can stack from statements in a Linq query and that will probably help you out here.
var query = from f in db.Foos
from f2 in f.Foos
where f.Name == "Two"
select f2;
Which produces.
SELECT [t1].[FooId],
[t1].[Name],
[t1].[ParentFooId]
FROM [dbo].[Foos] AS [t0], [dbo].[Foos] AS [t1]
WHERE ([t0].[Name] = #p0) AND ([t1].[ParentFooId] = [t0].[FooId])
You could alternatively do:
var query = from f in db.Foos
where (from fo in db.Foos
where fo.Name == "Two"
select fo.ParentId).Contains(f.ParentId)
select f;
This should result in something like:
SELECT [t1].[FooId],
[t1].[ParentFooId],
[t1].[Name]
FROM [dbo].[Foos] AS [t1]
WHERE [t1].[ParentFooId] IN (SELECT [t0].[ParentFooId]
FROM [dbo].[Foos] AS [t0]
WHERE[t0].[Name] = #p0)
May differ a bit (possibly an Exists()depending on your model)...I don't have a profiler window handy.
Try this:
var siblings = DataContext.Foos.Where(a => a.FooID == 3)
.Select(b => Foos.Where(b => Foos.ParentFooID == a.ParentFooID));
Assert.AreEqual(3, siblings.Count());

Categories

Resources