I'm confused about how to change this query to LINQ
select
CONTENT
from
(
select
CONTENT,
CAM_ID,
max(CAM_ID) over (partition by DOCUMENT_ID) MAX_ID
from
T_CAM_REVISION
where
DOCUMENT_ID = '101'
)
where
CAM_ID = MAX_ID
so I can get a single value of content.
There is no way to do max(...) over (...) in LINQ. Here is an equivalent query:
var maxCamID =
context.T_CAM_REVISION
.Where(rev => rev.DOCUMENT_ID == "101")
.Max(rev => rev.CAM_ID);
var query =
from rev in context.T_CAM_REVISION
where rev.CAM_ID == maxCamID
where rev.DOCUMENT_ID == "101"
select rev.CONTENT;
If you want only a single result:
var result =
context.T_CAM_REVISION
.First(rev => rev.CAM_ID == maxCamID
&& rev.DOCUMENT_ID == "101")
.CONTENT;
Related
I need to get one value of the q2.RoomId in this linq query as below and pass it to string variable . and is it possible to set alias column name for select ?
var result = from q1 in _db.DormApplications
join q2 in _db.DormRooms
on q1.DormRoomId equals q2.Id
where q1.Poster == username && q1.Review == EnableType.YES
&& now > q1.Sdate && now <q1.Edate
select new { q1.Name, q1.Sdate, q1.Edate, q1.DormRoomId,
q2.RoomId };
I tried this to get q2.RoomId ,
String room = result[4].ToString();
but still cannot work ,please anyone can help me ?
If you know the query will only return one row you can write:
var result = (from q1 in _db.DormApplications
join q2 in _db.DormRooms
on q1.DormRoomId equals q2.Id
where
q1.Poster == username && q1.Review == EnableType.YES
&& now > q1.Sdate && now <q1.Edate
select
new {
q1.Name,
q1.Sdate,
q1.Edate,
q1.DormRoomId,
q2.RoomId
}).FirstOrDefault();
var roomId = result.RoomId;
var Name = result.Name;
In my .NET Core app, I have the following in LINQ:
return await db.ApplicationUsers.Where(u=>u.Name.Contains(name) && !u.Deleted && u.AppearInSearch)
.OrderByDescending(u => u.Verified)
.Skip(page * recordsInPage)
.Take(recordsInPage)
.Select(u => new UserSearchResult()
{
Name = u.Name,
Verified = u.Verified,
PhotoURL = u.PhotoURL,
UserID = u.Id,
Subdomain = u.Subdomain
}).ToListAsync();
which translates to the following SQL:
SELECT [t].[Name], [t].[Verified],
[t].[PhotoURL], [t].[Id],
[t].[Subdomain]
FROM
(SELECT [u0].*
FROM [AspNetUsers] AS [u0]
WHERE (((CHARINDEX('khaled', [u0].[Name]) > 0) OR ('khaled' = N''))
AND ([u0].[Deleted] = 0))
AND ([u0].[AppearInSearch] = 1)
ORDER BY [u0].[Verified] DESC
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY ) AS [t]
But due to performance issues, Microsoft support suggested that I only query columns of fixed length (not varchar(max)). I was asked to change the SQL query to:
SELECT [t].[Name], [t].[Verified],
[t].[PhotoURL] , [t].[Id], [t].[Subdomain]
FROM
(Select u0.Name, u0.Verified, u0.PhotoURL, u0.id, u0.Subdomain,
u0.Deleted, u0.AppearInSearch FROM [AspNetUsers] ) As [u0]
WHERE (((CHARINDEX('khaled', [u0].[Name]) > 0) OR ('khaled' = N''))
AND ([u0].[Deleted] = 0))
AND ([u0].[AppearInSearch] = 1)
ORDER BY [u0].[Verified] DESC
OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY ) AS [t]
Which is a SELECT on another SELECT. Unfortunately I don't know how to do it in LINQ. Can someone please guide me how to make the second SQL query in LINQ?
Thank you
First build the inner select:
var s1 = from u in db.AspNetUsers
select new UserSearchResult
{
Name = u.Name,
Verified = u.Verified,
PhotoURL = u.PhotoURL,
UserID = u.Id,
Subdomain = u.Subdomain
};
then use it in the outer select:
return await (from u1 in s1
where u.Name.Contains(name) && !u.Deleted && u.AppearInSearch
orderby u.Verified
select u1)
.Skip(page * recordsInPage)
.Take(recordsInPage);
When you make the output of select query .ToList(), the output is a list again. Over this list you can apply another .Select(). So, as in your previous query, you can do it as:
return await db.ApplicationUsers.Where(u=>u.Name.Contains(name) && !u.Deleted && u.AppearInSearch)
.OrderByDescending(u => u.Verified)
.Skip(page * recordsInPage)
.Take(recordsInPage)
.Select(u => new UserSearchResult()
{
Name = u.Name,
Verified = u.Verified,
PhotoURL = u.PhotoURL,
UserID = u.Id,
Subdomain = u.Subdomain
})
.ToList()
.Select(<your new query>)
.ToListAsync();
I'm new in Linq, and I want to convert this sql Query to Linq Format.
This is the SQL format
select *
from investorwallets iw
where transactionid in
(select investordepositid from investordeposits)
or transactionid in
(select withdrawalid from investorwithdrawals)
or transactionid in
(select paymentdistributionid from paymentdistributions)
I've looked on this SO Question too, but no luck for me
EDIT
This is what I have tried. I use Linqpad for testing it
from iw in Investorwallets
where (
from id in Investordeposits // I got error from here
select id.investordepositid
)
Anyone can help me?
Thank you
The most direct is:
from iw in investorwallets
where investordeposits.Any(iten => item.investordepositid == iw.transactionid) ||
investorwithdrawals.Any(iten => item.withdrawalid == iw.transactionid) ||
paymentdistributions.Any(item => item.paymentdistributionid == iw.transactionid)
select iw;
However you can also union the results and then do .Contains:
var ids = investorwithdrawals.Select(item => item.investordepositid)
.Union(investorwithdrawals.Select(item => item.withdrawalid))
.Union(paymentdistributions.Select(item => item.paymentdistributionid));
var result = investorwallets.Where(item => ids.Contains(item.transactionid));
List<investorwallet> investorwallets = GetInvestorwallets();
List<investordeposit> investordeposits = GetInvestordeposits();
List<investorwithdrawal> investorwithdrawals = GetInvestorwithdrawals();
List<paymentdistribution> paymentdistributions = GetPaymentdistribution();
List<investorwallet> newList = investorwallets.Where(x => investordeposits.Any(y=>y.investordepositid == x.transactionid)
|| investorwithdrawals.Any(y => y.withdrawalid == x.transactionid)
|| paymentdistributions.Any(y => y.paymentdistributionid == x.transactionid)).ToList();
I have a SQL query :
SELECT [Paypoint]
,[Department]
,[EmployeeCode]
,[Gender]
,[EmployeeTitle]
,[Initials]
,[Surname]
,[ItemsIssuedDate]
,[ItemsIssuedStockNumber]
FROM [MyTable] AS a
WHERE
(
[ItemsIssuedDate] = ( SELECT max([ItemsIssuedDate])
FROM [MyTable] AS b
WHERE a.[Paypoint] = b.[Paypoint]
AND a.[Department] = b.[Department]
AND a.[EmployeeCode] = b.[EmployeeCode]
AND a.[Gender] = b.[Gender]
AND a.[Surname] = b.[Surname]
)
How would one get the comparitive LINQ query ? I cannot use the SQL query as the Data is already in a DataSet, and now needs to be modified further...
I have attempted, but this does not work :
var query = from a in excelTable
where
(
from c in excelTable
group c by new
{
c.Paypoint,
c.EmployeeCode
} into g
where string.Compare(a.Paypoint, g.Key.Paypoint) == 0 && string.Compare(a.EmployeeCode, g.Key.Paypoint) == 0
select g.Key.Paypoint
)
select a;
var query = from a in MyTable
group a by new {
a.Paypoint,
a.Department,
a.EmployeeCode,
a.Gender,
a.Surname
} into g
select g.OrderByDescending(x => x.ItemsIssuedDate)
//.Select(x => new { required properties })
.First();
You can also select anonymous object with required fields only. Up to you.
Your most direct with the SQL query will be:
var query =
from a in excelTable
let maxIssueDate =
(from b in excelTable
where a.Paypoint == b.Paypoint &&
a.Department == b.Department &&
a.EmployeeCode == b.EmployeeCode &&
a.Gender == b.Gender &&
a.Surname == b.Surname
select b.ItemsIssueDate).Max()
where a.ItemsIssueDate == maxIssueDate
select a;
What is in and not in equals in LINQ to SQL?
For example
select * from table in ( ...)
and
select * from table not in (..)
What is equal to the above statement in LINQ to SQL?
You use, where <list>.Contains( <item> )
var myProducts = from p in db.Products
where productList.Contains(p.ProductID)
select p;
Or you can have a list predefined as such:
int[] ids = {1, 2, 3};
var query = from item in context.items
where ids.Contains( item.id )
select item;
For the 'NOT' case, just add the '!' operator before the 'Contains' statement.
I'm confused by your question. in and not in operate on fields in the query, yet you're not specifying a field in your example query. So it should be something like:
select * from table where fieldname in ('val1', 'val2')
or
select * from table where fieldname not in (1, 2)
The equivalent of those queries in LINQ to SQL would be something like this:
List<string> validValues = new List<string>() { "val1", "val2"};
var qry = from item in dataContext.TableName
where validValues.Contains(item.FieldName)
select item;
and this:
List<int> validValues = new List<int>() { 1, 2};
var qry = from item in dataContext.TableName
where !validValues.Contains(item.FieldName)
select item;
Please Try This For SQL Not IN
var v = from cs in context.Sal_Customer
join sag in context.Sal_SalesAgreement
on cs.CustomerCode equals sag.CustomerCode
where
!(
from cus in context.Sal_Customer
join
cfc in context.Sal_CollectionFromCustomers
on cus.CustomerCode equals cfc.CustomerCode
where cus.UnitCode == locationCode &&
cus.Status == Helper.Active &&
cfc.CollectionType == Helper.CollectionTypeDRF
select cus.CustomerCode
).Contains(cs.CustomerCode) &&
cs.UnitCode == locationCode &&
cs.Status == customerStatus &&
SqlFunctions.DateDiff("Month", sag.AgreementDate, drfaDate) < 36
select new CustomerDisasterRecoveryDetails
{
CustomerCode = cs.CustomerCode,
CustomerName = cs.CustomerName,
AgreementDate = sag.AgreementDate,
AgreementDuration = SqlFunctions.DateDiff("Month", sag.AgreementDate, drfaDate)
};
Please Try This For SQL IN
context.Sal_PackageOrItemCapacity.Where(c => c.ProjectCode == projectCode && c.Status == Helper.Active && c.CapacityFor.Contains(isForItemOrPackage)).ToList();