Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Join Query Using Linq In VB.net

Im trying to convert a SQL Query to a linq query in vb. But Im have some trouble getting the syntax correct.

Original Query

SELECT b.* 
FROM History_Table_B b 
INNER JOIN Employee e ON b.EmployeeId = e.EmployeeId 
INNER JOIN Company c ON e.CompanyId = c.CompanyId 
WHERE e.AncillaryId = @AncillaryPersonId 
AND c.AncillaryId = @AncillaryCompanyId
AND (b.EndDate is null OR b.EndDate >= convert(date, GetDate()))

My Linq

Dim result = From b In context.H_Table_B
             Join employee In context.Employees
             On b.EmployeeId Equals (employee.EmployeeId)
             Join company In context.Companies
             On employee.CompanyId Equals (company.CompanyId) 
             Where employee.AncillaryId Equals(iPerId) 
             And company.AncillaryId Equals (iCompanyId) 
             And ((b.EndDate Is Nothing) Or (b.EndDate Equals(DateTime.Today)))
like image 424
Antarr Byrd Avatar asked Sep 13 '12 16:09

Antarr Byrd


People also ask

Can we use joins in LINQ?

relational tables. In a LINQ query expression, join operations are performed on object collections. Object collections cannot be "joined" in exactly the same way as two relational tables.

Can you use LINQ in VB net?

The Language Integrated Query (LINQ), which is pronounced as “link”, was introduced in the . NET Framework 3.5 to provide query capabilities by defining standardized query syntax in the . NET programming languages (such as C# and VB.NET). LINQ is provided via the System.

In which statement the LINQ query is executed in VB?

LINQ queries are always executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution. You can also force a query to execute immediately, which is useful for caching query results.


2 Answers

On where condition you can not use Equals (Operator) like Join LINQ query. Here Equals is a method of object class so you can access using '.' e.g. employee.AncillaryId.Equals(iCompanyId)

And Also one more thing in Where condition for new line VB.net required '_'.

e.g.

From b In context.H_Table_B
         Join employee In context.Employees
         On b.EmployeeId Equals (employee.EmployeeId)
         Join company In context.Companies
         On employee.CompanyId Equals (company.CompanyId) 
         Where employee.AncillaryId.Equals(iPerId) _ 
         And company.AncillaryId.Equals(iCompanyId) _
         And ((b.EndDate Is Nothing) Or (b.EndDate.Equals(DateTime.Today)))
like image 174
Jignesh Thakker Avatar answered Sep 30 '22 08:09

Jignesh Thakker


I think you're just missing a dot - try:

...b.EndDate.Equals(DateTime.Today)
like image 29
Dave Doknjas Avatar answered Sep 30 '22 07:09

Dave Doknjas