I have a model with a List<System.Drawing.Color>, as I mentioned, which comes to use in the Seed() like this:
protected override void Seed(DatabaseContext context)
{
var somethings = new List<Something>
{
new Something
{
Name="blah blah", Colors= { Color.Black, Color.Red }
}
};
}
And as long as I have the Colors over there like that, I always recieve
Object reference not set to an instance of an object. at line var somethings = new List<Something>.
When I remove the Colors, it goes away and everything works perfectly, what causes this and how can I solve this problem?
Thanks.
EDIT:
Something‘s model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
namespace MVCApplication7
{
public class Something
{
public int SomethingID { get; set; }
public string Name { get; set; }
public List<Color> Colors { get; set; }
}
}
Controller:
........
private DatabaseContext db = new DatabaseContext();
//
// GET: /Home/
public ViewResult Index()
{
return View(db.Somethings.ToList());
}
View: (I’m sure it’s irrelavent because the debugger shows the Colors is empty.
@foreach (var itemColor in item.Colors)
{
Html.Raw(itemColor.ToString());
}
Global.asax
.........
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Database.SetInitializer<DatabaseContext>(new DatabaseInitializer());
}
Chances are your
Somethingconstructor is returning without setting theColorsproperty to an empty list. Your collection initializer is just callingColors.Add(Color.Black)and thenColors.Add(Color.Red)– that’s not going to work if theColorsproperty is returning a null reference.Either set it to an empty list to start with (e.g. in the constructor) or create a new list and set the property itself:
It’s important that you understand the difference between the above code and your original. Your code is currently equivalent to (within the
List<Something>collection initializer):My code above is equivalent to:
See the difference?