0

我的知识是.Net 非常缺乏。任何有关以下方面的帮助将不胜感激:

我有一个客户模型:

public class CustomerModel
{

private DBEntities db = new DBEntities();

public List<CustomerModel> CustomerResultModel { get; set; }

[Required]
[DisplayName("Customer Number")]
public long ID { get; set; }

[StringLength(50)]
public string Firstname { get; set; }

[StringLength(50)]
public string Organisation { get; set; }

[StringLength(500)]
[DisplayName("Address Line 1")]
public string AddressLine1 { get; set; }

[StringLength(50)]
[Required(ErrorMessage = "A Postcode is required")]
public string Postcode { get; set; }

public CustomerModel GetCustomerResults(string q)
{
    CustomerModel model = new CustomerModel();

    var res = from s in db.CMUCustomers select s;

    foreach (var result in res)
    {
        CustomerModel modelres = new CustomerModel();

        modelres.ID = result.ID;
        modelres.CustomerName = result.Firstname;
        modelres.AddressLine1 = result.AddressLine1;
        modelres.Postcode = result.Postcode;
        modelres.Organisation = result.Organisation;

        model.CustomerResultModel.Add(modelres);
    }

    return model;
  }

}

在我的控制器中,我有:

private CustomerModel customerResults = new CustomerModel();

public ViewResult Search(string q)
{

CustomerModel model = customerResults.GetCustomerResults(q);
return View(model);

}

但是,我在“model.CustomerResultModel.Add(modelres);”上遇到错误 声明“对象引用未设置为对象的实例。”。对我可能做错的事情有什么建议吗?

谢谢

4

1 回答 1

2

它告诉您没有实例化 List 的错误,您需要在定义类的构造函数时或在分配值之前使用 List 实例化属性

如果你想在构造函数中

public CustomerModel ()
{
    this.CustomerResultModel  = new List<CustomerModel>()
}
于 2012-05-09T13:47:18.343 回答