使用Entity Framework和MVC3搜索记录

时间:2012-05-09 13:37:05

标签: asp.net .net asp.net-mvc-3 linq entity-framework

我的知识是.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);'上收到错误声明'对象引用未设置为对象的实例。'。对我可能做错的任何建议?

由于

1 个答案:

答案 0 :(得分:2)

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

如果你想进入构造函数

public CustomerModel ()
{
    this.CustomerResultModel  = new List<CustomerModel>()
}