I'm playing around with MVC3, trying to create small test projects which simulate problems that I anticipate I will encounter in a larger project I'm migrating from PHP. I keep getting a "NullReferenceException" on instantiating the "model" variable in the project with the elements below:
Model:
public class MainModel
{
public IEnumerable<Chemical> chemicals { get; set; }
}
public class Chemical
{
public int ChemicalId { get; set; }
public string Name { get; set; }
public virtual ICollection<Hazard> Hazards { get; set; }
}
public class Hazard
{
public int HazardId { get; set; }
public string Description { get; set; }
public virtual ICollection<Chemical> Chemicals { get; set; }
}
Controller:
public class MainController : Controller
{
public ActionResult Index()
{
var h1 = new Hazard { HazardId = 1, Description = "Flammable" };
var h2 = new Hazard { HazardId = 2, Description = "Carcinogen" };
var h3 = new Hazard { HazardId = 3, Description = "Water Reactive" };
var model = new [] {
new Chemical { ChemicalId = 1, Name = "Benzene", Hazards = {h1, h2}},
new Chemical { ChemicalId = 2, Name = "Sodium", Hazards = { h3 } },
new Chemical { ChemicalId = 3, Name = "Chloroform", Hazards = { h2 } },
new Chemical { ChemicalId = 4, Name = "Water" }
}; //NULL EXCEPTION THROWN HERE
return View(model);
}
}
So, I have two questions:
- Why do I keep getting the NullReferenceException, and how could it be fixed?
- In writing this code, I used this StackOverFlow Page as a starting point. Why is this okay, but what I wrote is not? Granted, I didn't test this code, but the author seems very competent.
Thanks!