Reputation: 177
I have an ICollection in my 'UserViewModel':
public ICollection<userpractice> userpractices { get; set; }
In my controller I am trying to add a userpractice to this collection in the viewmodel:
user user = db.users.Find(id);
UserViewModel uservm = new UserViewModel();
foreach (var up in user.userpractices)
{
uservm.userpractices.Add(up);
}
I get an error saying 'Object reference not set to an instance of an object.' I dont know why because the up is definitely correctly assigned to a populated userpractice.
uservm.userpractices is null if that helps. But I think that should be null at first as the viewmodel doesnt have any userpractices in the collection!
Upvotes: 1
Views: 147
Reputation: 14432
Yes, it is perfectly normal that uservm.userpractices
is null
at first. That's why you need to create a new instance of the collection before adding items to it. Example:
List<string> items;
items.Add("test"); //Object reference exception
First do this:
items = new List<string>();
items.Add("test"); //works
Upvotes: 4