One of the slower parts of fetching data from a database is the transport of the data from the DBMS to your local process. Hence you should not transport more values than you actually plan to use.
Your Table
has zero or more Availabilities
. Your database implements this by giving the Availability table a foreign key to the Table
that it belongs to.
So if you have a table with Id 4, which has 100 Availabilities
, and you would query the Table
with its Availabilities
using a Join
and Include
you would transfer the foreign key Availability.TableId a 100 times, while you already know they will all have the value of Table.Id
. You even know this value, because you asked for table with Id 4.
Hence, unless you plan to Update retrieved values, always use Select instead of querying complete classes.
Back to your question
Given a tableId, you want information of the table together with (some or all) its Availabilities.
Thanks to entity framework you don't have to use Join
. If you use the collections, entity framework will do the join for you.
var tableWithAvailabilities = myDbContext.Tables
.Where(table => table.TableId == tableId)
.Select(table => new
{
// select only the properties you plan to use
Id = table.TableId,
Num = table.Num,
...
Availabilities = table.Availabilities
.Where(availability => ...) // if you don't want all Availabilities
.Select(availability => new
{
// again: select only the properties you plan to use
// not needed, you know it equals Table.TableId
// Id = availability.TableId,
Date = availability.DayRes,
Available = availability.Avialable,
})
.ToList(),
});
Entity framework knows which Join is needed for this. One of the nicer things when using the Collections instead of a Join is that you make your database more abstract: you really are thinking of a Table
that has zero or more Availabilities
. It is a shortage of a DBMS that it needs two tables to implement this. If your internal tables changes, for instance the name of the foreign key, your query does not change, because you don't use the foreign key
If you are not planning to update a fetched value, then it is seldom wise to fetch