How to convert following SQL query to Lambda expression? - linq

I have a following SQL query how can I convert to lambda expression
select * from ContractItems
where ID in (SELECT distinct contractItemId from ContractPackageItems
where contractPackageId in (SELECT ID from ContractPackage
where ContractID = 680))
from the above query I need to know if row exist or not. If row exist then return true.
-TIA
---Update---
Here is what I got but it is not working
(from contractItem in _entities.ContractItems
where contractItem.ID == (from contractPackageItems in _entities.ContractPackageItems
where contractPackageItems.ContractPackageID == (from contractPackage in _entities.ContractPackages where contractPackage.ContractID == contractId select contractPackage.ID) select contractPackageItems.ContractItemId).Distinct()).Any();

Will this not do what you want?
var results = (from ci in _entities.contractItems
join cpi in _entities.contractPackageItems on ci.ID equals cpi.contractItemId
join cp in _entities.contractPackage on cpi.contractPackageId equals cp.ID
where cp.ContractID = 680
select ci).Any();

Related

how to write a Oracle view with this query?

I am using oracle 11g. I want to query with 3 queries.
First one, it is the main. Select to find condition.
Select role, name from tablerole where name is not null and ID=#param1;
This query will return #role with 2 level (admin and user)
The 2 other sub queries will base on this condition.
Up on the first query.
If role='admin' then select*from tablescreen where name is not null and ID=#param1;
If role='user' then select*from tablescreen where name='2';
#param1 is given when I call this view or when I using.
I consider it will be view or function or procedure best for this query.
How to write this query that can accept an input parameter into the query for looping source and return output where matched condition.
Thanks for your kindness.
Nam hmoob.
As far as I understood the question, that would be a view that consists of two select statements:
one that uses condition for admin
another one for user
The first query you posted will be used in a join with the tablescreen table. Something like this:
create or replace view v_role as
-- select for ADMIN
select r.id, s.whatever
from tablescreen s join tablerole r on r.id = s.id
where s.name is not null
and r.role = 'admin'
union all
-- select for USER
select r.id, s.whatever
from tablescreen s join tablerole r on r.id = s.id
where s.name = '2'
and r.name = 'user';
Or, as Zynon suggested, without union:
select r.id, s.whatever
from tablescreen s join tablerole r on r.id = s.id
where ( s.name is not null
and r.role = 'admin'
)
or ( s.name = '2'
and r.name = 'user'
);
You'd then use it as
select * from v_role v where v.id = &param1;

JPQL query with having oracle db

I am using jpql jpa eclipselink Following query wont work :
SELECT c FROM TableA c WHERE c.forumId = :forumId AND c.isDefault = true HAVING MAX (c.validFrom)
The error im getting "The expression is not a valid conditional expression"
The HAVING clause only works with a GROUP BY expression.
The HAVING clause allows for the results of a GROUP BY to be filtered.
Your question is:
i want o get max validFrom how can i make expression ot of this
But you can make a query without GROUP BY and HAVING to do what you want:
select c from TableA c WHERE c.validFrom = (
SELECT MAX(c2.validFrom)
FROM TableA c2
WHERE c2.Id = c.Id AND c.forumId = :forumId AND c.isDefault = true
)
If you would like to use GROUP BY and HAVING, you can do:
SELECT c FROM TableA c WHERE c.validFROM = (
SELECT MAX(validFROM)
FROM TableA
WHERE forumId = :forumId AND isDefault = true
GROUP BY validFROM
HAVING validFROM=c.validFROM
)

Linq how to join tables with a where clause on each table and a count

The following LINQ query isn't allowed when I use multiple where elements - it stops liking the 'into':
var query =
from ph in _db.PlayHits
join ua in _db.UserAgents on ph.UserAgentId equals ua.UserAgentId
where (ph.VideoId == 1 && ua.AgentString.Contains("test"))
into hits
select new
{
ResultCount = hits.Count()
};
Any idea why or how I amend this?
The equivilent sql I want is:
select count(*) as ResultCount
from Playhits ph
join UserAgents ua on ph.UserAgentId = ua.UserAgentId
where ph.VideoId = 1
and ua.AgentString like '%test%'
To my understanding, counting of the results can be done using the extension methond Count as follows.
var query =
from ph in _db.PlayHits
join ua in _db.UserAgents on ph.UserAgentId equals ua.UserAgentId
where (ph.VideoId == 1 && ua.AgentString.Contains("test"));
int Result = query.Count();

LINQ query (or lambda expression) to return records that match a list

I have a list of strings (converted from Guid) that contains the ID's of items I want to pull from my table.
Then, in my LINQ query, I am trying to figure out how to do an in clause to pull records that are in that list.
Here is the LINQ
var RegionRequests = (from r in db.course_requests
where PendingIdList.Contains(r.request_state.ToString())
select r).ToList();
It builds, but I get a run error: "System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression".
I would prefer to compare guid to guid, but that gets me nowhere.
Can this be converted to a lambda expression? If that is best, how?
LINQ to Entites tries to convert your expression to an SQL Statement. Your server didn't know the stored procedure ToString().
Fix:
var regionRequests =
from r in db.course_requests.ToList()
where PendingIdList.Contains(r.request_state.ToString())
select r;
With db.course_requests.ToList() you force LINQ to materialize your database data (if big table, you gonna have a bad time) and the ToString() is executed in the object context.
You stated: I have a list of strings (converted from Guid) ...
Can you NOT convert them into strings and keep it as a List< System.Guid>?? Then you can do this (assuming PendingIdGuidList is List< System.Guid>:
var regionRequets = (from r in db.course_requests
join p in PendingIdGuidList on u.request_state equals p
select r).ToList();
Edited to add:
I ran a test on this using the following code:
var db = new EntityModels.MapleCreekEntities();
List<System.Guid> PendingIdGuidList =
new List<System.Guid>() {
System.Guid.Parse("77dfd79e-2d61-40b9-ac23-36eb53dc55bc"),
System.Guid.Parse("cd409b96-de92-4fd7-8870-aa42eb5b8751")
};
var regionRequets = (from r in db.Users
join p in PendingIdGuidList on r.Test equals p
select r).ToList();
Users is a table in my database. I added a column called Test as a Uniqueidentifier data type, then modified 2 records with the following Guids.
I know it's not exactly a 1:1 of what the OP is doing, but pretty close. Here is the profiled SQL statement:
SELECT
[Extent1].[ID] AS [ID],
[Extent1].[UserLogin] AS [UserLogin],
[Extent1].[Password] AS [Password],
[Extent1].[Test] AS [Test]
FROM [dbo].[Users] AS [Extent1]
INNER JOIN (SELECT
cast('77dfd79e-2d61-40b9-ac23-36eb53dc55bc' as uniqueidentifier) AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
UNION ALL
SELECT
cast('cd409b96-de92-4fd7-8870-aa42eb5b8751' as uniqueidentifier) AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable2]) AS [UnionAll1] ON [Extent1].[Test] = [UnionAll1].[C1]

Join statement in Linq to Sql

I need to write Join statment after writing query in linq
example :
var Query = (from Tab in Db.Employees
select Tab)
as i have some cases to perform join operation so
i need to do it on this Query Query.Join(Join with another Table like Department); I need the Syntax
if (DeptID != -1){ Query.Join(Join with table Department where FkDeptID = DeptID); }
Consider the usage of join in the LINQ 'query syntax':
from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}
Something like this?
var results = (from q in Query
join m in myList on q.SomeID = m.SomeID
select unknown);
Try using this query:
var Query =
from e in Db.Employees
join d in Db.Departments on e.FkDeptID equals d.DeptID into departments
select new
{
Employee = e,
Department = departments.SingleOrDefault(),
};
This works assuming that when e.FkDeptID == -1 that there is no record in the Departments table and in that case Department would be assigned null.
You should never have more than one department for an employee so I've used SingleOrDefault rather than FirstOrDefault.

Resources