When i create an event with a relationship (many to many) with addresses i get the error: Object reference not set to an instance of an object [duplicate]
I've got a class Events that has a relationship with addresses, this is a many-to-many relationship. When I try to add the address to my Event it gives the error:
Object reference not set to an instance of an object.
Here is my code :
EVENT CLASS
public class Event
{
public int EventID { get; set; }
public string EventName { get; set; }
public string EventImage { get; set; }
public DateTime EventDate { get; set; }
public int ItemID { get; set; }
public virtual Item Item { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
ADDRESS CLASS
public class Address
{
public int Address_id { get; set; }
public string Address_street { get; set; }
public int Address_housenumber { get; set; }
public string Address_bus { get; set; }
public Nullable<int> Messages_id { get; set; }
public virtual ICollection<Event> Events { get; set; }
}
In my controller on the line with "viewEvent.Addresses.Add(address);" I get the error. When I hover on address it has the correct values but it keeps saying object reference not set...
المحلول
You're not instantiating your ICollection. When you attempt to add an address, your Addresses variable is null which causes the NullReferenceException. Initialize it to a concrete type:
if(viewEvent.Addresses == null)
{
viewEvent.Addresses = new List<Address>();
}
viewEvent.Addresses.Add(addres1);
نصائح أخرى
Add this line above the line that's failing:
viewEvent.Addresses = new List<Address>();
The issue is that you don't currently have a listing of addresses that's been initialized so you need to build one first, then you can add to it.