How do I write this query in linq VB.NET?
select top 15 count(1), A.Latitude, A.Longitude
from Bairro A
inner join Empresa B on B.BairroID = A.BairroID
where A.CidadeID = 4810
group by A.Latitude, A.Longitude
order by COUNT(1) desc
I reached this code:
Dim TopBairros = (From A In Bairros _
Join B In New BO.Empresa().Select On B.BairroID Equals A.BairroID Group A By A.Latitude, A.Longitude Into g = Group _
Select g Distinct _
Order By g.Count Descending).Take(15)
Each row has a array collection containing repeatly the same objects with the count number. Example:
row 0: array of 874 same objects
row 1: array of 710 same objects
and so on... How do I do to return only ONE object per row?
Try this:
var query = from a in context.Bairro
where a.CidadeID == 4810
join b in context.Empresa on a.BairroID equals b.BairroID
group a by new { a.Latitude, a.Longitude } into grouped
orderby grouped.Count() descending
select new { grouped.Key.Latitude,
grouped.Key.Longitude,
Count = grouped.Count() };
var top15 = query.Take(15);
Related
I am trying to fetch the results from the DB using the Entity Framework using the below SQL query:
SELECT
Header_Id,
Header_Number, Details_Id,
Details_Header_Date,
(SELECT TOP 1 c.[Comment_Description] FROM [Comment] c
WHERE c.[Comment_CarrierId] = i.[Header_CarrierId] AND c.[Comment_ParentEntityId] = i.[Header_Id]
ORDER BY c.Comment_AddedOn DESC) AS 'HeaderComments',
CONCAT(ht.[HeaderTracker_Reason], ' ', ht.[HeaderTracker_Notes]) AS 'RejectedComments',
at.[InternalComments] AS 'InternalComments',
CASE i.[Header_Status]
WHEN 'Pending' THEN ar.[HeaderTracker_ApprovedLvl] END AS 'ApprovedLevel',
CASE i.[Header_Status]
WHEN 'Pending' THEN ar.[HeaderTracker_DueBy] END AS 'ApprovedDueDate'
FROM [Header] i
LEFT OUTER JOIN [Details] ii
ON i.[Header_Id] = ii.[Details_HeaderId]
INNER JOIN [Carrier] t
ON t.[Carrier_Id] = i.[Header_CarrierId]
LEFT OUTER JOIN [HeaderTracker] ht
ON ht.[HeaderTracker_HeaderId] = i.[Header_Id] AND ht.[HeaderTracker_Type] = 'Rejected'
LEFT OUTER JOIN [AdjustmentTracker] at
ON at.[DetailsId] = ii.[Details_Id]
LEFT OUTER JOIN [HeaderTracker] ar
ON ar.[HeaderTracker_HeaderId] = i.[Header_Id]
AND i.[Header_Status] IN ('Paid', 'Pending', 'Approved', 'PaidWithAdj')
AND ar.[HeaderTracker_IsPending] = 1
The result output should be using LINQ query / LAMBDA expression
The following code is what I tried: (not sure how TOP 1 and CASE would come here + if & is also valid here)
var statuses = new string[] { "Paid", "Pending", "Approved", "PaidWithAdj" };
var hdrdet =
(
from hdr in dbContext.Headers
join det in dbContext.Details on hdr.Header_Id equals det.Header_Id into hdrdet
from h in hdrdet.DefaultIfEmpty()
join carr in dbContext.Carriers on hdr.Carrier_Id equals carr.Header_Carrier_Id into carrs
from c in carrs.DefaultIfEmpty()
join hdrtk in dbContext.HeaderTracker on hdr.Header_Id equals hdrtk.HeaderTracker_HeaderId && hdrtk.HeaderTracker_Type equals "Rejected" into hdrtks
from k in hdrtks.DefaultIfEmpty()
join adjt in dbContext.AdjustmentTracker on adjt.DetailsId equals det.Details_Id into adjts
from a in adjts.DefaultIfEmpty()
join pnd in dbContext.HeaderTracker on pnd.HeaderTracker_HeaderId equals hdr.Header_Id && hdr.Header_Status contains(statuses) && pnd.[HeaderTracker_IsPending] equals 1 into pnds
from p in pnds.DefaultIfEmpty()
select new
{
hdrid = Header_Id,
hdrnumber = Header_Number, Details_Id,
det_date = Details_Header_Date,
reason = HeaderTracker_Reason + ' ' + HeaderTracker_Notes,
intcomments = InternalComments
}
)
I have a SQL query that takes a subquery as a parameter for a left join.
SELECT tblfLeaseDetail.Lease_Detail_ID,
tblfPayment.Payment_Date,
tblfAuthorization.Authorized,
tblvVendor.Vendor_Name,
tblvCounty.County
FROM tblfLeaseDetail
LEFT
JOIN tblfPayment
ON tblfPayment.Lease_Detail_ID = tblfLeaseDetail.Lease_Detail_ID
AND tblfPayment.Payment_ID =
( SELECT TOP 1
Payment_ID
FROM tblfPayment
WHERE tblfPayment.Lease_Detail_ID = tblfLeaseDetail.Lease_Detail_ID
ORDER BY Payment_Date DESC
)
LEFT
JOIN tblfAuthorization
ON tblfAuthorization.Lease_Detail_ID = tblfLeaseDetail.Lease_Detail_ID
AND tblfAuthorization.Authorization_ID =
( SELECT TOP 1
Authorization_ID
FROM tblfAuthorization
WHERE tblfAuthorization.Lease_Detail_ID = tblfLeaseDetail.Lease_Detail_ID
ORDER BY Authorized_Date DESC
)
LEFT JOIN tblvVendor
on tblvVendor.Vendor_ID = tblfLeaseDetail.Vendor_ID
LEFT JOIN tblvCounty
on tblvCounty.County_ID = tblfLeaseDetail.County_ID
I'm trying to convert it to LINQ. So far this is what I've done:
var leaseList = (from l in leases.tblfLeaseDetails
join a in leases.tblfAuthorizations on l.Lease_Detail_ID equals a.Lease_Detail_ID into la
from jla in
(from aj in leases.tblfAuthorizations
where aj.Lease_Detail_ID == l.Lease_Detail_ID
orderby aj.Authorized_Date descending
select aj.Authorization_ID).Take(1).DefaultIfEmpty()
join p in leases.tblfPayments on l.Lease_Detail_ID equals p.Lease_Detail_ID into lp
from jlp in
(from pj in leases.tblfPayments
where pj.Lease_Detail_ID == l.Lease_Detail_ID
orderby pj.Payment_Date descending
select pj.Payment_ID).Take(1).DefaultIfEmpty()
join v in leases.tblvVendors on l.Vendor_ID equals v.Vendor_ID into lv
from jlv in lv.DefaultIfEmpty()
join c in leases.tblvCounties on l.County_ID equals c.County_ID into lc
from jlc in lc.DefaultIfEmpty()
select new LeaseViewModel()
{
Lease_Detail_ID = l.Lease_Detail_ID,
Vendor_Name = jlv.Vendor_Name,
County = jlc.County,
Authorization = jla.Authorized,
Payment_Date = jlp.Payment_Date
}).Distinct()
This returns me an error at jla.Authorized and jlp.Payment_Date:
'int' does not contain a definition for 'Authorized' and no extension method 'Authorized' accepting a first argument of type 'int' could be found
The same error goes for Payment_Date.
Why are jla and jlp being considered ints? How can I make this query work?
EDIT:
This is the final and working LINQ query:
var leaseList = (from l in leases.tblfLeaseDetails
join a in leases.tblfAuthorizations on l.Lease_Detail_ID equals a.Lease_Detail_ID into la
from jla in la.DefaultIfEmpty()
where jla.Authorization_ID == (from aj in leases.tblfAuthorizations
where aj.Lease_Detail_ID == l.Lease_Detail_ID
orderby aj.Authorized_Date descending
select aj.Authorization_ID).Take(1).FirstOrDefault()
join p in leases.tblfPayments on l.Lease_Detail_ID equals p.Lease_Detail_ID into lp
from jlp in lp.DefaultIfEmpty()
where jlp.Payment_ID == (from pj in leases.tblfPayments
where pj.Lease_Detail_ID == l.Lease_Detail_ID
orderby pj.Payment_Date descending
select pj.Payment_ID).Take(1).FirstOrDefault()
join v in leases.tblvVendors on l.Vendor_ID equals v.Vendor_ID into lv
from jlv in lv.DefaultIfEmpty()
join c in leases.tblvCounties on l.County_ID equals c.County_ID into lc
from jlc in lc.DefaultIfEmpty()
select new LeaseViewModel()
{
Lease_Detail_ID = l.Lease_Detail_ID,
Lease_ID = l.Lease_ID,
XRef_Lease_ID = l.XRef_Lease_ID,
Vendor_Name = jlv.Vendor_Name,
Description = l.Description,
County = jlc.County,
Amount = l.Amount,
Payment_Due_Date = l.Payment_Due_Date,
Lease_Type = l.Lease_Type.ToString(),
Location_ID = l.Location_ID,
Active = l.Active,
Expiration_Date = l.Expiration_Date,
Authorization = jla.Authorized,
Payment_Date = jlp.Payment_Date
}).Distinct();
That is because you are selecting Authorization_ID and Payment_ID which are of type int into jla and jlp respectively . Try the below query and let me know how it worked for you.
var leaseList = (from l in leases.tblfLeaseDetails
join a in leases.tblfAuthorizations on l.Lease_Detail_ID equals a.Lease_Detail_ID into la
from jla in
(from aj in leases.tblfAuthorizations
where aj.Lease_Detail_ID == l.Lease_Detail_ID
orderby aj.Authorized_Date descending
select aj).Take(1).DefaultIfEmpty()
join p in leases.tblfPayments on l.Lease_Detail_ID equals p.Lease_Detail_ID into lp
from jlp in
(from pj in leases.tblfPayments
where pj.Lease_Detail_ID == l.Lease_Detail_ID
orderby pj.Payment_Date descending
select pj).Take(1).DefaultIfEmpty()
join v in leases.tblvVendors on l.Vendor_ID equals v.Vendor_ID into lv
from jlv in lv.DefaultIfEmpty()
join c in leases.tblvCounties on l.County_ID equals c.County_ID into lc
from jlc in lc.DefaultIfEmpty()
select new LeaseViewModel()
{
Lease_Detail_ID = l.Lease_Detail_ID,
Vendor_Name = jlv.Vendor_Name,
County = jlc.County,
Authorization = jla.Authorized,
Payment_Date = jlp.Payment_Date
}).Distinct()
I have to convert it to Linq in vb.net. I am new to sql to linq. Guidance welcomed
select CONVERT(VARCHAR(10),a.StartDt,112) datenew,
COUNT(distinct(b.EmployerAccountOid)) companymoved,
COUNT(distinct(c.EmployerAccountOid)) companyfailed,
COUNT(distinct(d.ProductAccountOid)) planmoved,
COUNT(distinct(e.ProductAccountOid)) planfailed
from ebp.MgnCOREDCDataGroupMigrationRun a
left join ebp.MgnCOREDCMigrationRun b
on a.MigrationRunID = b.MigrationRunID
And TypeCd = 1 and a.MigrationStatusCd = 4
left join ebp.MgnCOREDCMigrationRun c
on a.MigrationRunID = c.MigrationRunID
and TypeCd = 1 and a.MigrationStatusCd = 5
left join ebp.MgnCOREDCMigrationRun d
on a.MigrationRunID = d.MigrationRunID
and TypeCd = 2 and a.MigrationStatusCd = 4
left join ebp.MgnCOREDCMigrationRun e
on a.MigrationRunID = e.MigrationRunID
and TypeCd = 2 and a.MigrationStatusCd = 5
group by CONVERT(VARCHAR(10),a.StartDt,112)
I tried to convert it to Linq with fail.
Dim query1= (From migrationgroup In UnitOfWork.DbContext.Set( Of MgnCOREDCDataGroupMigrationRun)()
Group Join migration In UnitOfWork.Set(of MgnCOREDCMigrationRun)() On migrationgroup.MigrationRunID Equals migration.MigrationRunID And migrationgroup.TypeCode = 1 And migrationgroup.MigrationStatusCode=4 _
Into migrationErrorGrp = Group
From mgeg In migrationErrorGrp.DefaultIfEmpty()
Group Join migration1 In UnitOfWork.Set(of MgnCOREDCMigrationRun)() On migration1.MigrationRunID Equals migrationgroup.MigrationRunID And migrationgroup.TypeCode = 1 And migrationgroup.MigrationStatusCode=4 _
Into migrationErrorGrp1 = Group
From mgeg1 In migrationErrorGrp1.DefaultIfEmpty()
Group Join migration2 In UnitOfWork.Set(of MgnCOREDCMigrationRun)() On migration2.MigrationRunID Equals migrationgroup.MigrationRunID And migrationgroup.TypeCode = 2 And migrationgroup.MigrationStatusCode=5 _
Into migrationErrorGrp2 = Group
From mgeg2 In migrationErrorGrp2.DefaultIfEmpty()
Group Join migration3 In UnitOfWork.Set(of MgnCOREDCMigrationRun)() On migration3.MigrationRunID Equals migrationgroup.MigrationRunID And migrationgroup.TypeCode = 2 And migrationgroup.MigrationStatusCode=5 _
Into migrationErrorGrp3 = Group
From mgeg3 In migrationErrorGrp3.DefaultIfEmpty()
Group By CONVERT(VARCHAR(10),migrationgroup.StartDt,112) into g
select New With{CONVERT(VARCHAR(10),migrationgroup.StartDt,112),
Count(distinct(migration.EmployerAccountOid)) ,
Count(distinct(migration1.EmployerAccountOid)),
Count(distinct(migration2.EmployerAccountOid)),
Count(distinct(migration3.EmployerAccountOid))}).ToList()
If IsNothing(query1) Then
Return Nothing
End If
coredcmigrationhistory =
From coredcmigrationrow In query1()
My query is non-queryable. Can anybody guide me where I m goin wrong
How do I write the following sql join in linq?
select Campaign.CampaignName, COUNT(*) as total
from Campaign join CampaignAsset
on CampaignAsset.CampaignId=Campaign.CampaignId
where Campaign.UserProfileId=65
Group By Campaign.CampaignName
Try This :
YourDatabaseName dataContext = new YourDatabaseName();
var result = from c in dataContext.Campaign
join ca in dataContext.CampaignAsset on c.CampaignId equals ca.CampaignId into j1
from j2 in j1.DefaultIfEmpty()
where c.UserProfileId = 65
group j2 by c.CampaignName into grouped
select new { CampaignName = grouped.Key, Count = grouped.Count() };
I can't figure out that linq to entity query syntax. My problem is that if the value of the Calls table is null then noting comes up, I want to make something like a left join to get 'all' rows from the Calls table.
I tried to group it but I can't figure out the correct way to write it.
Dim TicketQuery As ObjectQuery = From c In EnData.Customer _
Join t In EnData.Calls On t.CustomerID Equals c.CustomerID _
Join Status In EnData.Lists On t.Status Equals Status.ListValue _
Join Project In EnData.Lists On t.Project Equals Project.ListValue _
Join Priorty In EnData.Lists On t.Priority Equals Priorty.ListValue _
Where c.Status > -1 And t.Status > -1 And Status.ListType = 1 And Project.ListType = 3 And Priorty.ListType = 2 _
Select New With {c.CustName, t.CallID, t.CallDate, t.CallTime, t.Description, Key .Status = Status.ListText, Key .Project = Project.ListText, t.DateModified, Key .Priority = Priorty.ListText}
How can I fix that?
Similar question: Linq to Sql: Multiple left outer joins
Microsoft Documentation: http://msdn.microsoft.com/en-us/library/bb918093.aspx#Y916
LINQ Examples from: http://msdn.microsoft.com/en-us/vbasic/bb737909
Left Outer Join
A so-called outer join can be expressed with a group join. A left outer joinis like a cross join, except that all the left hand side elements get included at least once, even if they don't match any right hand side elements. Note how Vegetables shows up in the output even though it has no matching products.
Public Sub Linq105()
Dim categories() = {"Beverages", "Condiments", "Vegetables", "Dairy Products", "Seafood"}
Dim productList = GetProductList()
Dim query = From c In categories _
Group Join p In productList On c Equals p.Category Into Group _
From p In Group.DefaultIfEmpty() _
Select Category = c, ProductName = If(p Is Nothing, "(No products)", p.ProductName)
For Each v In query
Console.WriteLine(v.ProductName + ": " + v.Category)
Next
End Sub
For left join in VB.net we can use Let
Dim q =
(From item In _userProfileRepository.Table
Let Country = (From p In _countryRepository.Table Where p.CountryId = item.CurrentLocationCountry Select p.Name).FirstOrDefault
Let State = (From p In _stateRepository.Table Where p.CountryId = item.CurrentLocationCountry Select p.Name).FirstOrDefault
Let City = (From p In _stateRepository.Table Where p.CountryId = item.CurrentLocationCountry Select p.Name).FirstOrDefault
Where item.UserId = item.ProfileId.ToString)
After the left join we can use group by
Dim q2 =
(From p In q Group p By p.Country, p.State, p.City Into Group
Select New With
{
.Country = Country,
.State = State,
.City = City,
.Count = Group.Count
}).ToList()