Translate an specific SQL query to Linq - c#

I need your help because I'm trying to translate a very specific SQL query to Linq but I can't do it by myself because of an ISNULL clause that I don't know how to put it in LINQ. Here is the SQL query:
select f.fId as alias1, f.fDate, f.IniHour, f.EndHour, f.Cap, f.Ocup
, isnull(
(select o.Cap - o.Ocup
from table2 o
left outer join table3 r on o.id = r.id
where o.fId=f.id and r.fieldI = #value)
, 1) as alias2
from table1 f
inner join table4 t on f.id=t.id
and f.fDate+cast(fIniHour as datetime) > Dateadd(Hour,2,Getdate())
order by f.fDate,f.IniHour
The problem is how to put the ISNULL in the Select clause in the Linq query. Could you, please, help me with this issue?
Thank you in advanced.

Related

Multiple table join with multiple table where clause

I have a query that's something like this.
Select a.*
from table1 a
inner join table2 b on a.field1 = b.field1
inner join table3 c on b.field2 = c.field2
where b.field4 = beta and c.field5 = gamma.
On LINQ, I tried to do that this way:
var query = (from a in table1
join b in table2 on a["field1"] equals b["field1"]
join c in table3 on b["field2"] equals c["field2"]
where (b["field4"] == beta && c["field5"] == gamma)
select a).ToList();
But for some reason, when I try to do this I get an error that says that the entity "table2" doesn't have the field Name = "field5", as though as the where clause was all about the last joined table and the other ones were unaccessible. Furthermore, the compiler doesn't seem to notice neither, because it lets me write c["field5"] == gamma with no warning.
Any ideas? Am I writing this wrong?
Thanks
See these links:
How to: Perform Inner Joins (C# Programming Guide)
What is the syntax for an inner join in linq to sql?
Why you don't create View in database, and Select your data from View in LINQ?

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]))

Convert from LINQ to SQL query to SQL query

I want to convert LINQ to SQL to SQL query. I know simple LINQ to SQL but don't know about more.
Given below is my Linq to Sql and I want to convert it into Sql query.
from objSql in objContext.DoctorNotes
join objCreatedU in objContext.Users on objSql.CreatedByUserFK equals objCreatedU.UserID into objCU
from tblC in objCU.DefaultIfEmpty()
join objModifiedU in objContext.Users on tblC.ModifiedByUserFK equals objModifiedU.UserID into objMU
from tblM in objMU.DefaultIfEmpty()
select new DoctorNoteBind(objSql)
{
CreatedBy = tblC.UserName,
ModifiedBy = tblM.UserName
}).ToList();
The .DefaultIfEmpty() are used to represent LEFT JOINs (http://msdn.microsoft.com/en-us/library/ms187518(v=sql.100).aspx). You'd expect the equivalent SQL to take the following form:
SELECT
U1.UserName AS CreatedBy,
U2.UserName AS ModifiedBy
FROM
DoctorNotes DN
LEFT JOIN Users U1 ON
U1.UserID = DN.CreatedByUserFK
LEFT JOIN Users U2 ON
U2.UserID = DN.ModifiedByUserFK
-- WHERE ?
-- ORDER BY ?

How to translate SQL statement with multiple join conditions based on subquery to LINQ

This might be one of those situations where plain SQL commands are better than LINQ. Here's a simplified version of the SQL statement I'm trying to translate:
SELECT * FROM IDTable AS idt
INNER JOIN NameTable AS nt ON nt.IDTableID=idt.Id
AND nt.Id= (SELECT TOP(1) Id
FROM NameTable AS nt2
WHERE nt2.IDTableID=11 ORDER BY nt2.DateInserted DESC)
I have the LINQ query to pull records when just joining on IDs and I've seen how to join on multiple columns, but I have no idea how to plug the subquery into the mix.
If this isnt entirely clear, please let me know and I'll edit to elaborate.
Maybe something like this?
var results = from id in db.IDTable
join n in db.NameTable on id.Id equals n.IDTableID
where n.Id = (
from n2 in db.NameTable
where n2.IDTableID = 11
orderby n2.DateInserted desc
).First()
select new { id, n };

Linq To Sql Left outer join - filtering null results

I'd like to reproduce the following SQL into C# LinqToSql
SELECT TOP(10) Keywords.*
FROM Keywords
LEFT OUTER JOIN IgnoreWords
ON Keywords.WordID = IgnoreWords.ID
WHERE (DomainID = 16673)
AND (IgnoreWords.Name IS NULL)
ORDER BY [Score] DESC
The following C# Linq gives the right answer.
But I can't help think I'm missing something (a better way of doing it?)
var query = (from keyword in context.Keywords
join ignore in context.IgnoreWords
on keyword.WordID equals ignore.ID into ignored
from i in ignored.DefaultIfEmpty()
where i == null
where keyword.DomainID == ID
orderby keyword.Score descending
select keyword).Take(10);
the SQL produced looks something like this:
SELECT TOP (10)
[t0].[DomainID]
, [t0].[WordID]
, [t0].[Score]
, [t0].[Count]
FROM [dbo].[Keywords] AS [t0]
LEFT OUTER JOIN
( SELECT 1 AS [test]
, [t1].[ID]
FROM [dbo].[IgnoreWords] AS [t1]
) AS [t2]
ON [t0].[WordID] = [t2].[ID]
WHERE ([t0].[DomainID] = 16673)
AND ([t2].[test] IS NULL)
ORDER BY [t0].[Score] DESC
How can I get rid of this redundant inner selection?
It's only slightly more expensive but every bit helps!
I think you can do something like this to eliminate the left join and maybe get more efficiency:
var query = (from keyword in context.Keywords
where keyword.DomainID == ID
&& !(from i in context.IgnoreWords select i.ID).Contains(keyword.WordID)
orderby keyword.Score descending
select keyword)
.Take(10);

Categories

Resources