-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。
是的,我有uderid的userdetails。我試過你的代碼,仍然有相同的錯誤 – kandroid