Pooki Foo Pooki Foo - 2 months ago 25
C# Question

how to use linq with two related entities?

Hello i got a problem while using two related entities in a dotnet project

i have two entities table and reservation and i need to get the table that is reserved for tomorrow but the date is seted in the reservation table
here's the code

public class Table
{
public int Id { get; set; }
public bool isAvailable { get; set; }
public int Numero { get; set; }
public virtual ICollection<Reservation> IReservation { get; set; }
}

public class Reservation
{
public DateTime DateReservation { get; set; }
public int Id { get; set; }
public string Nom { get; set; }
public virtual Table table { get; set; }
}
public class RestaurantContext :DbContext
{
public DbSet<Table> tTable { set; get; }
public DbSet<Reservation> tReservation { set; get; }
public RestaurantContext() : base("RestaurentDB") {
}
}
class TableRepository
{
RestaurantContext rc = null;

public TableRepository()
{
rc = new RestaurantContext();
}
public void Commit()
{
rc.SaveChanges();
}
public void AddTable(Table m)
{
rc.tTable.Add(m);
}

public IEnumerable<Table> GetAllTables() {
return rc.tTable.ToList();
}
public IEnumerable<Table> GetTablesReserverdTomorrow() {
....
}


Here i need to get the table which are reserved for tomorrow
i tried

var res=rc.tReservation.Where(r => (r.DateReservation == DateTime.Today.AddDays(1))).ToList();
var res1 = rc.tTable.Select(r => res.Contains(r.Id));
return res1;


but it seems theres an error


Argument1: Cannot convert from int to Reservation

Answer

you could try to use navigation within your query, like:

return rc.tReservation
    .Include(reservation => reservation.Table)
    .Where(r => (r.DateReservation == DateTime.Today.AddDays(1)))
    .Select(reservation => reservation.table).toList();
Comments