Trying to populate lists from my database as follows, here is the controller:
namespace TimetableSystem.Controllers
{
public class AvailabilityController : Controller
{
TimetableSystemEntities systemDB = new TimetableSystemEntities();
public ActionResult Index()
{
var parkList = new List<String>();
var parkQry = from p in systemDB.Parks
orderby p.ParkID
select p.ParkName;
parkList.AddRange(parkQry);
ViewBag.Park = parkList;
here is the park model:
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace TimetableSystem.Models
{
public class ParkModel
{
[Key]
public int ParkID { get; set; }
public string ParkName { get; set; }
}
}
and here is the TimetableSystemEntities model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace TimetableSystem.Models
{
public class TimetableSystemEntities : DbContext
{
public TimetableSystemEntities() : base("DefaultConnection") { }
public DbSet<Department> Departments { get; set; }
public DbSet<Module> Modules { get; set; }
public DbSet<Request> Requests { get; set; }
public DbSet<Round> Rounds { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<ParkModel> Parks { get; set; }
public DbSet<BuildingModel> Buildings { get; set; }
public DbSet<RoomModel> Rooms { get; set; }
}
}
But when I debug and move to the Availability page, I am given this error:
[System.Data.SqlClient.SqlException] {"Invalid object name 'dbo.ParkModels'."}
Not sure what is happening here as I can't find 'ParkModels' anywhere in the project or the database, the model is ParkModel, the database table is Park.
My understanding of code-first is that by convention the model and table names need to match. In your case they don't so you need to specify the mapping.
[Table("Park")]
public class ParkModel
{
[Key]
public int ParkID { get; set; }
public string ParkName { get; set; }
}
Then your context should be:
DbSet<ParkModel> Parks { get; set; }