stats101
stats101

Reputation: 1877

Searching records with Entity Framework and MVC3

My knowledge is .Net is lacking tremendously. Any assistance on the following would be appreciated:

I have a Customer Model:

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

}

In my Controller I have:

private CustomerModel customerResults = new CustomerModel();

public ViewResult Search(string q)
{

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

}

I however get an error on 'model.CustomerResultModel.Add(modelres);' stating 'Object reference not set to an instance of an object.'. Any suggestions to what I could be doing wrong?

Thanks

Upvotes: 0

Views: 508

Answers (1)

Jorge
Jorge

Reputation: 18257

The error it's telling you that you don't have instanced the List, you need to instance the attribute with the List when you define the constructor of your class or before to assign the values

if you want to be in the constructor

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

Upvotes: 2

Related Questions