From a design standpoint, it is better to not have a copy of any table. A good design for this situation can be something like this.
public class Trip
{
public int ID {get; set;}
public string Destination {get; set;}
public DateTime DepartureDate {get; set;}
public string MeetPlace {get; set;}
public int NumberOfSeats {get; set;}
public int CreatedByUserID {get; set;}
public virtual ApplicationUser CreatedByUser {get; set;}
public virtual ICollection<TripReservation> Reservations {get;set;}
}
public class TripReservation
{
public int ID {get; set;}
public int TripID {get; set;}
public int UserID {get; set;}
public virtual Trip Trip {get; set;}
public virtual ApplicationUser User {get; set;}
}
then in your controller you can construct a view model with the number of seats available being
numberOfSeatsAvailable = trip.NumberOfSeats - trip.Reservations.Count();
If a reservation can reserve more than 1 seat, you can sum that from all reservations for that trip.
Example: ViewModel
public class TripReservationsViewModel
{
public Trip Trip { get; set; }
public int NumberOfSeatsAvailable { get; set; }
}
Example: Controller
public ActionResult TripDetails(int id)
{
var trip = db.Trips.FirstOrDefault(trip => trip.ID == id);
if (trip == null)
{
// Trip does not exist,
// Redirect the user to the trips home page
//
return RedirectToAction("Index");
}
var viewModel = new TripReservationsViewModel();
viewModel.Trip = trip;
viewModel.NumberOfSeatsAvailable = trip.NumberOfSeats - trip.Reservations.Count();
return View(viewModel);
}
Example: View
@model TripReservationsViewModel
<h1>Trip Details</h1>
<p>Seats available: @Model.NumberOfSeatsAvailable</p>
etc...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…