从数据库中检索数据时,对象引用未设置为对象的实例

时间:2014-04-13 22:15:43

标签: asp.net asp.net-mvc-4 nullreferenceexception

当我尝试通过Details操作方法从数据库中检索数据时遇到问题,并且我在表CompanyUserProfile之间存在一对多关系,而我正在使用实体框架我的模型是UserProfile

[Table("UserProfile")]
public class UserProfile
{

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserID { get; set; }
    public string UserName { get; set; }

    public Membership Membership { get; set; }
    public ICollection<Company> Companys { get; set; }
    public ICollection<UsersInRoles> UsersInRoles { get; set; }
    public ICollection<Comment> Comments { get; set; }
    public ICollection<Like> Likes { get; set; }

}

和公司

[Bind(Exclude = "CompanyID")]
public class Company
{
    [ScaffoldColumn(false)]
    public int CompanyID { get; set; }

    [Required(ErrorMessage = "Company Name is required")]
    [DisplayName("Company Name")]
    [StringLength(40)]
    public string CompanyName { get; set; }

    [Required(ErrorMessage = "Mobile Number is required")]
    [DisplayName("Mobile Number")]
    //[DataType(DataType.PhoneNumber)]
    public string CompanyPhoneNumber { get; set; }

    [Required(ErrorMessage = "Company Address is required")]
    [DisplayName("Company Address")]
    [StringLength(128)]
    public string CompanyAddress { get; set; }

    //must change in controller to view only the manager user
    [Required(ErrorMessage = "Manager Name is required")]
    [DisplayName("Manager")]
    public int UserID { get; set; }
    public UserProfile UserProfile { get; set; }

    public ICollection<Store> Stores { get; set; }
    public ICollection<Product> Products { get; set; }
}

控制器和详细信息操作方法

public ActionResult Details(int id = 0)
    {
        Company company = db.Companys.Find(id);
        string user = company.UserProfile.UserName;
        if (company == null)
        {
            return HttpNotFound();
        }
        return View(company);
    }

我设置string user = company.UserProfile.UserName;并设置一个断点,以查看返回的值是什么,每次都返回null并且它给我这个错误对象引用未设置为对象的实例所以是什么我做错了感谢任何帮助

2 个答案:

答案 0 :(得分:3)

您的公司检查需要在UserName访问之前,如下所示:

Company company = db.Companys.Find(id);

// do the null check first.
if (company == null)
{
 return HttpNotFound();
}

string user = company.UserProfile.UserName;

答案 1 :(得分:1)

试试这个:

public ActionResult Details(int id = 0)
{
    Company company = db.Companys.Where(c=>c.CompanyID ==id).Select(c=>c);
   //you can check if the value is null after
    if(company!=null)
    string user = company.UserProfile.UserName;
    else
    {
        return HttpNotFound();
    }
    return View(company);
}

希望它会对你有所帮助。