I am trying to convert a SQL statement to LINQ.
I have this as SQL:
SELECT mutDetail.*
FROM hallo.Mutatie as mut
JOIN hallo.MutatieDetail AS mutDetail ON mut.MutatieID = mutDetail.fkMutatieID
JOIN tblMedewerker AS med ON med.MedewerkerID = mut.fkMedewerkerID
JOIN tblKlant AS klant ON klant.KlantID = med.fkKlantID
WHERE mutDetail.BronCode = 'Personeelsnummer'
AND klant.KlantNummer = '78555522'
And this is my LINQ statement:
public IQueryable<Mutatie> GetMutatiesInstroom()
{
var mutaties = (from m in context.Mutatie
join mutDetail in context.MutatieDetail on m.MutatieID equals mutDetail.fkMutatieID
join med in context.tblMedewerker on m.fkMedewerkerID equals med.MedewerkerID
join klant in context.tblKlant on med.fkKlantID equals klant.KlantID
select m);
return mutaties;
}
But how to write the where statement in LINQ?
Thank you
I don't know what the problem was, but isn't it simple? Before select m:
where m.BronCode == "Personeelsnummer" && klant.KlantNummer == "8700"
Complete query as requested:
var mutaties = from m in context.Mutatie
join mutDetail in context.MutatieDetail on m.MutatieID equals mutDetail.fkMutatieID
join med in context.tblMedewerker on m.fkMedewerkerID equals med.MedewerkerID
join klant in context.tblKlant on med.fkKlantID equals klant.KlantID
where m.BronCode == "Personeelsnummer" && klant.KlantNummer == "8700"
select m;
It should go here:
public IQueryable<Mutatie> GetMutatiesInstroom()
{
var mutaties = (from m in context.Mutatie
join mutDetail in context.MutatieDetail on m.MutatieID equals mutDetail.fkMutatieID
join med in context.tblMedewerker on m.fkMedewerkerID equals med.MedewerkerID
join klant in context.tblKlant on med.fkKlantID equals klant.KlantID
where (mutDetail.BronCode == "Personeelsnummer" &&
klant.KlantNummer == "8700")
select m);
return mutaties;
}
Here is an example from microsofts documentation on how to add a filter in Linq statement.
var queryLondonCustomers = from cust in customers
where cust.City == "London"
select cust;
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/basic-linq-query-operations
right under section Filtering
Related
If the person you are searching is a CIA emplyee, take his CIAJobs.EmployerID, otherwise select People.ID
SELECT
case when CIAJobs.EmployeeID IS NULL then People.ID
else CIAJobs.EmployerID
end
FROM [FMO].[People] AS p
LEFT JOIN [FMO].[CIAJobs] j
ON (p.ID = j.[EmployeeID])
AND (j.[relationshipType] = '25a8d79d-377e-4108-8c92-0ef9a2e1ab63')
where p.ID = '1b66e032-94b2-e811-96e0-f48c508e38a2' // id of person you search for
OR
j.[EmployeeID] = '1b66e032-94b2-e811-96e0-f48c508e38a2' // id of person you search for
I tried doing this in Linq:
var a = from l in People
join x in CIAJobs
on l.Id equals x.EmployeeID && x.RelationshipTypeGuid equals Guid.Parse('25a8d79d-377e-4108-8c92-0ef9a2e1ab63')
into gcomplex
from xx in gcomplex.DefaultIfEmpty()
select (xx.EmployeeID == null) ? l.EmployeeId : x.EmployerID;
var b = a.ToList();
why does the query show an error because of this chunk: && x.RelationshipTypeGuid equals Guid.Parse('25a8d79d-377e-4108-8c92-0ef9a2e1ab63')
If I remove this part it shows no error.
Error is: operator && cannot be applied to operands of type Guid and Guid.
Can you help me correct the Linq query please logically and syntactically? Thank you.
You don't need join for multiple conditions in this scenario. Use this
var a = from l in People
join x in CIAJobs
.Where(z=>z.RelationshipTypeGuid
.Equals(Guid.Parse('25a8d79d-377e-4108-8c92-0ef9a2e1ab63')))
on l.Id equals x.EmployeeID
into gcomplex
from xx in gcomplex.DefaultIfEmpty()
select (xx.EmployeeID == null) ? l.EmployeeId : x.EmployerID;
var b = a.ToList();
But based on your problem statement this should do
var a = from l in People
join x in CIAJobs
on l.Id equals x.EmployeeID
into gcomplex
from xx in gcomplex.DefaultIfEmpty()
select (xx == null) ? l.EmployeeId : xx.EmployerID;
var b = a.ToList();
Case1:
var query = (from p in db.TblPost where (from q in db.TblThread
where q.LocationLocationid == locationID && q.CategoriesCategoryid == categoryID select q.Threadid).Contains(p.ThreadThreadid)
join r in db.TblThread on p.ThreadThreadid equals r.Threadid join s in db.TblUser on p.UserUserid equals s.Userid join t
in db.TblCategories on r.CategoriesCategoryid equals t.Categoryid join u in db.TblLocation on r.LocationLocationid
equals u.Locationid orderby r.CreatedTime descending
select new { p, r.Subject, r.EventAddress, r.EventClosetime, r.EventDate, r.EventDuration, r.EventStarttime,
r.EventTitle, r.IseventAllday, r.TargetUsers, r.CreatedTime, s.FirstName, s.MiddleName, s.LastName, t.Name,
u.Locationname, r.Isreadonly }).ToList();
OR
Case 2:
List<TblPost> _tblPost = new List<TblPost>();
_tblPost = (from p in db.TblPost select p).ToList();
List<TblThread> _tblThread = new List<TblThread>();
_tblThread = (from p in db.TblThread select p).ToList();
List<TblUser> _tblUser = new List<TblUser>();
_tblUser = (from p in db.TblUser select p).ToList();
List<TblLocation> _tblLocation = new List<TblLocation>();
_tblLocation = (from p in db.TblLocation select p).ToList();
List<TblCategories> _tblCategory = new List<TblCategories>();
_tblCategory = (from p in db.TblCategories select p).ToList();
var query = (from p in _tblPost where (from q in _tblThread where q.LocationLocationid == locationID
&& q.CategoriesCategoryid == categoryID select q.Threadid).Contains(p.ThreadThreadid) join r in _tblThread on p.ThreadThreadid
equals r.Threadid join s in _tblUser on p.UserUserid equals s.Userid join t in _tblCategory on r.CategoriesCategoryid equals
t.Categoryid join u in _tblLocation on r.LocationLocationid equals u.Locationid orderby r.CreatedTime descending
select new { p, r.Subject, r.EventAddress, r.EventClosetime, r.EventDate, r.EventDuration, r.EventStarttime,
r.EventTitle, r.IseventAllday, r.TargetUsers, r.CreatedTime, s.FirstName, s.MiddleName, s.LastName,
t.Name, u.Locationname, r.Isreadonly }).ToList();
I've these two codes which results the same. But, in case 2 i'm getting the result some quickly as compared to case 1. Which one should i need to follow?
Shall i follow case 2? is it right way to get huge data in Web.API?
SELECT ra.ResidentID, ra.RoomID, r.Number, ra.StartDate, p.FacilityID
FROM(
SELECT ResidentID, MAX(StartDate) AS max_start
FROM RoomAssignments
GROUP BY ResidentID
) m
INNER JOIN RoomAssignments ra
ON ra.ResidentID = m.ResidentID
AND ra.StartDate = m.max_start
INNER JOIN Rooms r
ON r.ID = ra.RoomID
INNER JOIN Person p
ON p.ID = ra.ResidentID
inner join ComplianceStage cs
ON cs.Id = p.ComplianceStageID
ORDER BY ra.EndDate DESC
I'm trying to figure out how to convert this to C# using LINQ. I'm brand new with C# and LINQ and can't get my subquery to fire correctly. Any chance one of you wizards can turn the lights on for me?
Update-----------------
I think I've got the jist of it, but am having trouble querying for the max startdate:
var maxQuery =
from mra in RoomAssignments
group mra by mra.ResidentID
select new { mra.ResidentID, mra.StartDate.Max() };
from ra in RoomAssignments
join r in Rooms on ra.RoomID equals r.ID
join p in Persons on ra.ResidentID equals p.ID
where ra.ResidentID == maxQuery.ResidentID
where ra.StartDate == maxQuery.StartDate
orderby ra.ResidentID, ra.StartDate descending
select new {ra.ResidentID, ra.RoomID, r.Number, ra.StartDate, p.FacilityID}
Following my LINQ to SQL Recipe, the conversion is pretty straight forward if you just follow the SQL. The only tricky part is joining the range variable from the subquery for max start date to a new anonymous object from RoomAssignments that matches the field names.
var maxQuery = from mra in RoomAssignments
group mra by mra.ResidentID into mrag
select new { ResidentID = mrag.Key, MaxStart = mrag.Max(mra => mra.StartDate) };
var ans = from m in maxQuery
join ra in RoomAssignments on m equals new { ra.ResidentID, MaxStart = ra.StartDate }
join r in Rooms on ra.RoomID equals r.ID
join p in Persons on ra.ResidentID equals p.ID
join cs in ComplianceStage on p.ComplianceStageID equals cs.Id
orderby ra.EndDate descending
select new {
ra.ResidentID,
ra.RoomID,
r.Number,
ra.StartDate,
p.FacilityID
};
I have following LINQ statement:
from o in Orders
join od in OrderDetails on o.OrderNumber equals od.OrderNumber
join r in RMAs on o.OrderNumber equals r.OrderNumber
join rd in RMADetails on r.RMAnumber equals rd.RMAnumber
from i in Inventory
where( a => ( od.SKU == a.LocalSKU)).DefaultIfEmpty()//error is here
where (r.Status != "Pending" && od.Adjustment == false)
select new
{
r.Status,
o.Name,
o.Company,
o.Address,
o.Address2,
o.City,
o.State,
o.Country,
o.Email,
o.Zip,
o.Phone,
o.ShipName,
o.ShipCompany,
o.ShipAddress,
o.ShipAddress2,
o.ShipCity,
o.ShipCountry,
o.ShipState,
o.ShipPhone,
o.ShipZip,
o.OrderNumber,
o.ShippingTotal,
OrderDate = o.OrderDate,
SerialNumbers = rd.SerialNumbers ?? "",
o.SourceOrderID
}
It's giving Invalid Where term. What I want to use LEFT OUTER JOIN having SQL Equivalent left join Inventory i on od.SKU = i.LocalSKU
Try this:
var qry = from o in Orders
join od in OrderDetails.Where(od=>od.Adjustment == false) on o.OrderNumber equals od.OrderNumber
join i in Inventory on i.LocalSKU equals od.SKU into grp
from g in grp.DefaultIfEmpty()
join r in RMAs.Where(r=>r != 'Pending') on o.OrderNumber equals r.OrderNumber
join rd in RMADetails on r.RMAnumber equals rd.RMAnumber
select new
{
//set of columns here
};
Problem: Am trying to rewrite this in Linq:
listOfUsersForReviewer is an IEnumerable<User>
int countOfGreenUsers = 0;
foreach (var user in listOfUsersForReviewer)
{
var u = (from reviewitems in context.ReviewItems
join groupaccountlinks in context.GroupAccountLinks on reviewitems.GroupAccountID equals groupaccountlinks.GroupAccountID
join reviews in context.Reviews on reviewitems.ReviewID equals reviews.ReviewID
join applications in context.Applications on reviews.ApplicationID equals applications.ApplicationID
join reviewers in context.Reviewers on applications.ResponsibleReviewerID equals reviewers.ReviewerID
join accounts in context.Accounts on groupaccountlinks.AccountID equals accounts.AccountID
join users in context.RBSUsers on accounts.UserID equals users.UserID
where
users.UserID == user.UserID &&
reviewers.FullyQualifiedLogin == fullyQualifiedLogin &&
reviews.ReviewStatusID == (byte)Enums.ReviewStatus.InProgress &&
reviewitems.ReviewItemStatusID == (byte)Enums.ReviewItemStatus.Unapproved
select reviewitems);
byte colour = (byte)Enums.UserStatusColour.Red;
if (u.Count() == 0)
{
colour = (byte)Enums.UserStatusColour.Green;
countOfGreenUsers++;
}
}
have tried to create an anonymous type, however this doesn't compile.
// select number of green users
var x = from user in listOfUsersForReviewer
from reviewitems in context.ReviewItems
join groupaccountlinks in context.GroupAccountLinks on reviewitems.GroupAccountID equals
groupaccountlinks.GroupAccountID
join reviews in context.Reviews on reviewitems.ReviewID equals reviews.ReviewID
join applications in context.Applications on reviews.ApplicationID equals applications.ApplicationID
join reviewers in context.Reviewers on applications.ResponsibleReviewerID equals
reviewers.ReviewerID
join accounts in context.Accounts on groupaccountlinks.AccountID equals accounts.AccountID
join users in context.RBSUsers on accounts.UserID equals users.UserID
where
users.UserID == user.UserID &&
reviewers.FullyQualifiedLogin == fullyQualifiedLogin &&
reviews.ReviewStatusID == (byte)Enums.ReviewStatus.InProgress &&
reviewitems.ReviewItemStatusID == (byte)Enums.ReviewItemStatus.Unapproved
select new
{
UserID = user.UserID,
CountOfGreen = reviewitems.Count()
};
Add grouping clause
var x = from user in listOfUsersForReviewer
from reviewitems in context.ReviewItems
join groupaccountlinks in context.GroupAccountLinks on reviewitems.GroupAccountID equals
groupaccountlinks.GroupAccountID
join reviews in context.Reviews on reviewitems.ReviewID equals reviews.ReviewID
join applications in context.Applications on reviews.ApplicationID equals applications.ApplicationID
join reviewers in context.Reviewers on applications.ResponsibleReviewerID equals
reviewers.ReviewerID
join accounts in context.Accounts on groupaccountlinks.AccountID equals accounts.AccountID
join users in context.RBSUsers on accounts.UserID equals users.UserID
where
users.UserID == user.UserID &&
reviewers.FullyQualifiedLogin == fullyQualifiedLogin &&
reviews.ReviewStatusID == (byte)Enums.ReviewStatus.InProgress &&
reviewitems.ReviewItemStatusID == (byte)Enums.ReviewItemStatus.Unapproved
group user by user.UserID into grouping
select new
{
UserID = grouping.Key,
CountOfGreen = grouping.Count()
};
I ended up rethinking me logic and split this query into 2 simpler ones.
Tools I used were: SQL Server Management Studio (graphical representation), Linqer and potentially Linqpad
And writing the query in English helped a lot.