I'm creating a system that draws routes using Bing Maps and ASP.Net. I want to store the postcodes for the stops on the route in a SQL Database and pass them over to the view using MVC.
However, querying the database doesn't return any results, even though the Database is popualted. I've used Debug.WriteLine in various parts of the code and deduced that though it's connecting to the database and querying the right table, when I initialise the DBContext in my controller, using ToList.Count
on it shows 0.
My code is as follows:
Controller - MapController.cs
private StopsDBContext db = new StopsDBContext();
public ActionResult Index()
{
Debug.WriteLine("***************************************************************************************");
Debug.WriteLine("--->" + db.Stops.ToList().Count + "<---"); // this shows 0
Debug.WriteLine("***************************************************************************************");
var Stops = from e in db.Stops
select e;
List<Stop> Model = Stops.ToList();
return View(Model);
}
Model - Stop.cs
public class Stop
{
public int ID { get; set; }
public string Name { get; set; }
public string Postcode { get; set; }
public Stop(int iD, string name, string postcode)
{
ID = iD;
Name = name;
Postcode = postcode;
}
public Stop() {}
}
public class StopLists
{
public IEnumerable<Stop> StopList { get; set; }
}
public class StopsDBContext : DbContext
{
public StopsDBContext()
{
Database.Log = s => Debug.WriteLine(s); //this shows the sql queries in the console
}
public DbSet<Stop> Stops { get; set; }
}
I've passed hardcoded data into the view before doing this so I know that part's right, and since it's running the query it must be connecting to the Database, so I'm not sure what I'm missing.
Thanks in advance
EDIT: Updated classes following advice from Dai
I've solved the error now. Thanks to everyone that replied for your advice.
Turns out my model and my table had different fields and I didn't realise, so the DBContext was searching for fields that didn't exist. Whoops.