Left Join Linq to Entity's Vb.net - vb.net

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

Related

LINQ to DATASET with Group Join and Group By (vb.net)

I've got 2 datatables and am trying to summarize the data in them using a left outer join. The join works fine with this code
Dim Journal = From entries In dt.AsEnumerable()
Join inccodes In dtGL.AsEnumerable()
On entries.Field(Of String)("GLCode") Equals inccodes.Field(Of String)("GLCode")
Group By keys = New With {Key .IncomeCode = entries.Field(Of String)("GLCode"), Key .IncomeDesc = .inccodes.Field(Of String)("GLCodeDesc")}
Into ChargeSum = Group, sm = Sum(entries.Field(Of Decimal)("Amount"))
Where sm <> 0
Select New GL_Journal With {.IncomeCode = keys.IncomeCode, .IncomeDesc = keys.IncomeDesc, .LineAmount = sm}
`
However, since I really want a Left Outer Join I want to use Group Join instead of Join.
As soon as I change the Join to Group Join the code in the Group by at ".inccodes.field(Of String)("GLCodeDesc")" has ".inccodes" highlighted with the error "'inccodes' is not a member of 'anonymous type'"
I've reviewed much documentation on Group By and Group Join but there is scant information on them together.
Any ideas? Would I have more options/success with the method syntax?
If i try to reproduce your query using a left outer join, I will do something like this :
Dim dt As New DataTable
dt.Columns.Add("GLCode", GetType(String))
dt.Columns.Add("Amount", GetType(Decimal))
dt.Rows.Add("111", 3251.21)
dt.Rows.Add("222", 125.79)
dt.Rows.Add("999", 10000)
Dim dtGL As New DataTable
dtGL.Columns.Add("GLCode", GetType(String))
dtGL.Columns.Add("GLCodeDesc", GetType(String))
dtGL.Rows.Add("111", "a")
dtGL.Rows.Add("222", "b")
dtGL.Rows.Add("333", "c")
Dim Journal = From entries In dt.AsEnumerable()
Group Join inccodes In dtGL.AsEnumerable()
On entries.Field(Of String)("GLCode") Equals inccodes.Field(Of String)("GLCode")
Into Group
From lj In Group.DefaultIfEmpty()
Group By keys = New With {Key .IncomeCode = entries.Field(Of String)("GLCode"), Key .IncomeDesc = lj?.Field(Of String)("GLCodeDesc")}
Into ChargeSum = Group, sm = Sum(entries.Field(Of Decimal)("Amount"))
Select New With {.IncomeCode = keys.IncomeCode, .IncomeDesc = keys.IncomeDesc, .LineAmount = sm}

SQL to Linq - NET CORE 5

I have a SQL Statement like this:
select
b.ActivityRecordId, b.ActivityName, b.ActivityDetail,
b.CustomerId, e.CustomerName,
b.JobStatusId, c.JobStatusName, b.EstimateStartDate,
b.EstimateFinishDate, b.StartedDateTime, b.FinishedDateTime,
a.ActivityRecordProgressId, a.CustomerContactId,
Concat(d.FirstName, ' ', d.MiddleName, ' ', d.LastName) as fullName,
a.Started, a.Finished, a.ActivityDescription,
g.ActivityTypeId, g.ActivityTypeName, a.ActivitySubTypeId, f.ActivitySubTypeName
from
ActivityRecordProgress a
right join
ActivityRecord b on a.ActivityRecordId = b.ActivityRecordId
left join
ActivitySubType f on a.ActivitySubTypeId = f.ActivitySubTypeId
left join
ActivityType g on f.ActivityTypeId = g.ActivityTypeId
left join
CustomerContact d on a.CustomerContactId = d.CustomerContactId
inner join
JobStatus c on b.JobStatusId = c.JobStatusId
inner join
Customer e on b.CustomerId = e.CustomerId
Then I tried to convert it to Linq:
var obj = (from a in _db.ActivityRecords
join b in _db.ActivityRecordProgresses on a.ActivityRecordId equals b.ActivityRecordId into ab
from p in ab.DefaultIfEmpty()
join c in _db.Customers on a.CustomerId equals c.CustomerId
join e in _db.CustomerContacts on c.CustomerId equals e.CustomerId
join d in _db.JobStatuses on a.JobStatusId equals d.JobStatusId
join f in _db.ActivitySubTypes on p.ActivitySubTypeId equals f.ActivitySubTypeId
join g in _db.ActivityTypes on f.ActivitySubTypeId equals g.ActivityTypeId
select new OutstandingActivityViewModel {
ActivityRecordId = p.ActivityRecordId,
ActivityName = a.ActivityName,
ActivityDetail = a.ActivityDetail,
CustomerId = a.CustomerId,
CustomerName = c.CustomerName,
JobStatusId = a.JobStatusId,
JobStatusName = d.JobStatusName,
EstimateStartDate = a.EstimateStartDate,
StartedDateTime = a.StartedDateTime,
EstimateFinishDateTime = a.EstimateFinishDate,
FinishedDateTime = a.FinishedDateTime,
FirstName = e.FirstName, MiddleName = e.MiddleName, LastName = e.LastName,
Started = p.Started, Finished = p.Finished,
ActivityTypeName = g.ActivityTypeName, ActivitySubTypeName = f.ActivitySubTypeName,
ActivityDescription = p.ActivityDescription
}).ToListAsync();
But the result is not the same. The SQL result is the right one. It only 4 records. But in Linq, it appears 6 records. I'm sure I did something wrong with the linq syntax.
Can anyone show me where the mistake in my syntax is?
Really appreciated - thank you.
Thanks for commenting my question. It was very useful.
Finally I found the answer after trial and error using SQL generated. Below is the answer for the Linq syntax:
var obj = (from a in _db.ActivityRecords
join b in _db.ActivityRecordProgresses on a.ActivityRecordId equals b.ActivityRecordId into leftsatu
from leftkesatu in leftsatu.DefaultIfEmpty()
join c in _db.ActivitySubTypes on leftkesatu.ActivitySubTypeId equals c.ActivitySubTypeId into leftdua
from leftkedua in leftdua.DefaultIfEmpty()
join d in _db.ActivityTypes on leftkedua.ActivitySubTypeId equals d.ActivityTypeId into lefttiga
from leftketiga in lefttiga.DefaultIfEmpty()
join e in _db.CustomerContacts on leftkesatu.CustomerContactId equals e.CustomerContactId into leftempat
from leftkeempat in leftempat.DefaultIfEmpty()
join f in _db.JobStatuses on a.JobStatusId equals f.JobStatusId
join g in _db.Customers on a.CustomerId equals g.CustomerId
select new OutstandingActivityViewModel
{
ActivityRecordId = a.ActivityRecordId,
ActivityName = a.ActivityName,
ActivityDetail = a.ActivityDetail,
CustomerId = a.CustomerId,
CustomerName = g.CustomerName,
JobStatusId = a.JobStatusId,
JobStatusName = f.JobStatusName,
EstimateStartDate = a.EstimateStartDate,
StartedDateTime = a.StartedDateTime,
EstimateFinishDateTime = a.EstimateFinishDate,
FinishedDateTime = a.FinishedDateTime,
FirstName = leftkeempat.FirstName,
MiddleName = leftkeempat.MiddleName,
LastName = leftkeempat.LastName,
Started = leftkesatu.Started,
Finished = leftkesatu.Finished,
ActivityTypeName = leftketiga.ActivityTypeName,
ActivitySubTypeName = leftkedua.ActivitySubTypeName,
ActivityDescription = leftkesatu.ActivityDescription
}
);
It will generate SQL like:
SELECT [a].[ActivityRecordId], [a].[ActivityName], [a].[ActivityDetail], [a].[CustomerId], [c0].[CustomerName], [a].[JobStatusId], [j].[JobStatusName],
[a].[EstimateStartDate], [a].[StartedDateTime], [a].[EstimateFinishDate] AS [EstimateFinishDateTime], [a].[FinishedDateTime],
[c].[FirstName], [c].[MiddleName], [c].[LastName],
[a0].[Started], [a0].[Finished], [a2].[ActivityTypeName], [a1].[ActivitySubTypeName], [a0].[ActivityDescription]
FROM [ActivityRecord] AS [a]
LEFT JOIN [ActivityRecordProgress] AS [a0] ON [a].[ActivityRecordId] = [a0].[ActivityRecordId]
LEFT JOIN [ActivitySubType] AS [a1] ON [a0].[ActivitySubTypeId] = [a1].[ActivitySubTypeId]
LEFT JOIN [ActivityType] AS [a2] ON [a1].[ActivitySubTypeId] = [a2].[ActivityTypeId]
LEFT JOIN [CustomerContact] AS [c] ON [a0].[CustomerContactId] = [c].[CustomerContactId]
INNER JOIN [JobStatus] AS [j] ON [a].[JobStatusId] = [j].[JobStatusId]
INNER JOIN [Customer] AS [c0] ON [a].[CustomerId] = [c0].[CustomerId]

Convert SQL Query to LINQ query/Lambda expression

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

Linq :Query Join And Equals( variable) Not Work

Dim ID_Section as Int32 = 10
Dim Query = From Book1 In db.Book1
Group Join Section In db.Section On CInt(Book1.ID_Section) Equals Section.ID_section _
And Section.ID_section Equals (ID_Section) Into Section_join = Group
From Section In Section_join.DefaultIfEmpty()
Select
Book1.ID_Book,
Book1.Name_Book,
ID_section = Section.ID_section,
Name_Section = Section.Name_Section
The error appears in the variable id_Section, since the Linq does not accept values ​​from the outside, as it seems to me of course.
Here Error :
And Section.ID_section Equals (ID_Section)
In SQL Query Use At :
Declare #ID_Section int
SELECT Book.ID_Book, Book.Name_Book, Section.ID_section, Section.Name_Section
FROM Book LEFT OUTER JOIN
Section ON Book.ID_Section = Section.ID_section and Section.ID_section = #ID_Section
where Book.ID_Book =1
Using Where on db.Section with lambda syntax:
Dim Query = From Book1 In db.Book1
Group Join Section In db.Section.Where(Function(s) s.ID_section = ID_Section)
On CInt(Book1.ID_Section) Equals Section.ID_section _
Into Section_join = Group
From Section In Section_join.DefaultIfEmpty()
Select
Book1.ID_Book,
Book1.Name_Book,
ID_section = Section.ID_section,
Name_Section = Section.Name_Section
Alternatively you can apply the Where to the Join results:
Dim Query = From Book1 In db.Book1
Group Join Section In db.Section
On CInt(Book1.ID_Section) Equals Section.ID_section _
Into Section_join = Group
From Section In Section_join.Where(Function(s) s.ID_section = ID_Section).DefaultIfEmpty()
Select
Book1.ID_Book,
Book1.Name_Book,
ID_section = Section.ID_section,
Name_Section = Section.Name_Section

sql to linq in vb.net

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