Ger Mc Ger Mc - 4 months ago 27
C# Question

LINQ and joins?

I have two tables

Cars
and
Bookings
and I wish to return the startdate and enddate from the
Bookings
table based on carId in the
Cars
table.
here are my tables

Cars

ID Make Model Size
----------- --------------- --------------- ---------------
1 BMW 5Series Medium
2 Dacia Duster Large
3 Ford Mustang Large


Bookings

ID CarID StartDate EndDate
----------- ----------- ---------- ----------
1 1 2017-02-01 2011-04-05
2 1 2017-05-11 2011-09-15
3 1 2017-09-09 2012-12-15
4 1 2017-07-12 2017-11-14
5 2 2017-01-16 2017-08-28


I was trying this but keep getting errors and am not sure how to proceed

string query3 = from c in db.Cars
join b in db.Bookings on c.ID equals b.CarID
select new { b.StartDate ,b.EndDate}.ToString();

Answer Source

I believe you want something like this:

var query3 = from c in db.Cars
join b in db.Bookings on c.ID equals b.CarID
select new { b.StartDate, b.EndDate};

var results = query3.ToList(); // ToList executes the query on the database
// results will be a List<a'> where a'> DateTime StartDate, DateTime EndDate