如何将对象添加到ICollection<>对象

时间:2011-09-16 09:11:37

标签: asp.net asp.net-mvc class

我有一个像这样的简单演示类......

员工

public class Employee
        {
            public string Name { get; set; }
            public string Email { get; set; }

        }

另一个类AddressDetails

public class AddressDetails
        {
            public string Address1 { get; set; }
            public string City { get; set; }
            public string State { get; set; }
        }

再加一个EmpAdd

public class EmpAdd 
        {
            public ICollection<Employee> Employees { get; set; }
            public ICollection<AddressDetails> AddressDetails { get; set; }
        }

好的,当我在课堂上传递一些像这样的值时..

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";

一切正常......

但是当我试图在EmpAdd中添加这两个时它给了我错误“对象引用未设置为实例”请帮助...这只是一个虚拟..我有7个实体,我面对同样的问题....

EmpAdd emp = new EmpAdd();
            emp.Employee.Add(newEmp);
            emp.AddressDetails.Add(newAddress);

3 个答案:

答案 0 :(得分:2)

emp.Employee和emp.AddressDetails未实例化。您需要创建一个实例化它们的构造函数

public class EmpAdd 
{
    public ICollection<Employee> Employees { get; set; }
    public ICollection<AddressDetails> AddressDetails { get; set; }
    public EmpAdd()
    {
        Employees = new List<Employee>();
        AddressDetails = new List<AddressDetails>();
    }
}

答案 1 :(得分:1)

您的ICollection属性永远不会被初始化。自动属性在您的属性后面实现一个字段,但仍需要将其分配给。 我建议你的属性是只读的(去除集合),自己实现它背后的字段,并在声明时初始化它:

private List<Employee> _employees = new List<Employee>();

public ICollection<Employee> Employees { 
    get
    {
        return _employees;
    }
}

答案 2 :(得分:0)

@Adrian Iftode的含义是:

EmpAdd emp = new EmpAdd();
        emp.Employee = newEmp;
        emp.AddressDetails = newAddress;
        emp.Employee.Add(newEmp);
        emp.AddressDetails.Add(newAddress);

这应该解决这个问题 无论如何,坚持@Menno van den Heuvel的建议。