【问题标题】:Searching records with Entity Framework and MVC3使用 Entity Framework 和 MVC3 搜索记录
【发布时间】:2012-05-09 13:37:05
【问题描述】:

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

谢谢

【问题讨论】:

  • 您在哪里添加此语句? private CustomerModel customerResults = new CustomerModel();

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


【解决方案1】:

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

如果你想在构造函数中

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

【讨论】:

  • 谢谢!那行得通!顺便提一句。我是以标准方式执行上述操作,还是在模型中包含模型列表是一种愚蠢的做法? (获取客户结果列表)
  • 这完全取决于您想要实现的目标,现在创建模型列表的属性是多余的,如果它是您可以在代码中毫无问题地处理的东西,但是如果在您看来exit 需要有这个属性,好好利用吧
猜你喜欢
  • 1970-01-01
  • 2020-12-15
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 2015-01-01
  • 2014-11-11
相关资源
最近更新 更多