inspile
inspile

Reputation: 35

Convert Join SQL to LINQ-to-SQL Method Syntax

I have a repository for a MVC 4 Web API to retrieve data from database using Linq to SQL Method Syntax. The code I have so far (its not much) for the a utility:

public IQueryable<Vehicle> Vehicles(int driverId_Vehicles)
{
    ...?...
}

I've put together an SQL query that would get the data from the database:

SELECT VEHICLE.*
FROM Vehicle
INNER JOIN DriverHabit
ON VEHICLE.Id=DriverHabit.VehicleId
WHERE DriverHabit.Id = driverId

I need assistance translating this query into the LINQ method syntax to return the IQueryable.

Upvotes: 0

Views: 166

Answers (2)

RAM
RAM

Reputation: 91

SELECT VEHICLE.* FROM Vehicle INNER JOIN DriverHabit ON VEHICLE.Id=DriverHabit.VehicleId WHERE DriverHabit.Id = driverId

var vehicle = from v in _context.vehicle              
          join dh in _context.driverhabit on v.Id equals dh.VehicleId
          where dh.Id = driverId
          select { v, dh }

return vehicle.ToList();

Upvotes: 0

Gert Arnold
Gert Arnold

Reputation: 109137

It looks like the association Vehicle - DriverHabit is 1:n. There should be a navtigation property DriverHabits in your Vehicle class, so you don't have to join. Just access the navigation property.

Upvotes: 1

Related Questions