i am having a simple demo class like this…
Employee
public class Employee
{
public string Name { get; set; }
public string Email { get; set; }
}
one more class AddressDetails
public class AddressDetails
{
public string Address1 { get; set; }
public string City { get; set; }
public string State { get; set; }
}
one more EmpAdd
public class EmpAdd
{
public ICollection<Employee> Employees { get; set; }
public ICollection<AddressDetails> AddressDetails { get; set; }
}
ok, when i am passing some values in class like this..
Employee newEmp = new Employee();
newEmp.Email = "temp@gmail.com";
newEmp.Name = "Judy";
AddressDetails newAddress = new AddressDetails();
newAddress.Address1 = "UK";
newAddress.City = "London";
newAddress.State = "England";
all works fine…
but when i am trying to add this two in EmpAdd it gives me error “Object reference not set to an instance” please help …this is just a dummy .. i have 7 entities in which i am facing the same problem….
EmpAdd emp = new EmpAdd();
emp.Employee.Add(newEmp);
emp.AddressDetails.Add(newAddress);
Your ICollection property is never initialized. The auto properties implement a field behind your property, but it still needs to be assigned to.
I suggest making your property read-only (get rid of the set), implement the field behind it yourself, and initialize it on declaration: