I am coding an MVC4 C# internet application and when I save an object to a list successfully, when I get a listing of this list in another function, the list is empty.
Here is my code:
public class House
{
public House()
{
Rooms = new List<Room>();
}
[Key]
public int id { get; set; }
public int StreetNumber { get; set; }
public string StreetName { get; set; }
public string City { get; set; }
public List<Room> Rooms { get; set; }
}
public class Room
{
[Key]
public int id { get; set; }
public int RoomNumber { get; set; }
public string RoomOwnersName { get; set; }
}
public class DatabaseContext : DbContext
{
public DbSet<House> Houses { get; set; }
public DbSet<Room> Rooms { get; set; }
}
Here is my code to create and add a room to a house:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int id, Room room)
{
if (ModelState.IsValid)
{
House houseToAddRoomsTo = db.Houses.Where(h => h.id == id).FirstOrDefault();
houseToAddRoomsTo.Rooms.Add(room);
db.SaveChanges();
return RedirectToAction("Index", id);
}
return View(room);
}
Here is my code to get a listing of the rooms in a house:
public ActionResult Index(int id)
{
RoomsViewModel roomsViewModel = new RoomsViewModel();
roomsViewModel.HouseID = id;
roomsViewModel.Rooms = db.Houses.Where(h => h.id == id).First().Rooms.ToList();
return View(roomsViewModel);
}
After I have created a room, and added this room to a house, and I call the Index method to view the rooms for a house, the list is empty.
Can I please have some help with this code?
Thanks in advance