-1

在下面的代码中,我有 country=1、school=2 和 course=3。但在那之后,当我试图分配类似的,userdata.UserCountry.CountryId=Convert.ToInt32(country)。它说“对象引用未设置为.......对象实例”表示空值。

[HttpPost]
    public ActionResult Settings(FormCollection frm)
    {

            UsersContext db = new UsersContext();

            var userdata = db.UserDetails.Where(k => k.UserId == WebSecurity.CurrentUserId).FirstOrDefault();

            string country = frm["UserCountry"]; // here I have 1.
            string school = frm["UserSchool"];
            string course = frm["UserCourse"];

            userdata.UserCountry.CountryId= Convert.ToInt32(country); // Here i have the null reference error.. !!
            userdata.UserSchool.SchoolId = Convert.ToInt32(school);
            userdata.UserCourse.CourseId = Convert.ToInt32(course);
            userdata.Link = frm["Link"];
            userdata.FullName = frm["FullName"];
            userdata.Email = frm["Email"];
            userdata.About = frm["About"];

            db.SaveChanges();

            return Content(Boolean.TrueString);
    }

这是模型:

public class UserDetail
{
    public int Id { get; set; }
    public int UserId { get; set; }
    [Required]
    [Display(Name="Full name")]
    public string FullName { get; set; }
    public string Link { get; set; }
    public bool? Verified { get; set; }

    [Required]
    [Display(Name="Email")]
    public string Email { get; set; }

    [Display(Name="About")]
    public string About { get; set; }
    public virtual School UserSchool { get; set; }
    public virtual Course UserCourse { get; set; }

    [Display(Name = "Country")]
    public virtual Country UserCountry { get; set; }

}

谁能帮我解决这个问题...plz。

4

1 回答 1

1

尝试在查询结果中包含相关实体:

 var userdata = db.UserDetails
                  .Include("UserCountry")
                  .Include("UserSchool")
                  .Include("UserCourse")
                  .Where(k => k.UserId == WebSecurity.CurrentUserId)
                  .FirstOrDefault();

顺便说一句,验证您是否确实拥有带有您搜索的 UserId 的 UserDetails。

于 2013-01-02T22:27:11.117 回答