您好,我是.Net MVC中的新程序员。您认为我在哪里犯错?我的代码不会更新我的数据。您能帮我解决这个问题吗?
public class MemberModel
{
public int UserID { get; set; }
public string UserName { get; set; }
public string UserSurname { get; set; }
public string UserPassword { get; set; }
public string UserEmail { get; set; }
}
public class UserinfoModel
{
public int UserInfoID { get; set; }
public Nullable<System.DateTime> DateOfBirth { get; set; }
public string PhoneNumber { get; set; }
public string Adress { get; set; }
public byte[] UserImage { get; set; }
public Nullable<int> fk_GenderID { get; set; }
public Nullable<int> fk_UserID { get; set; }
public virtual tbl_Gender tbl_Gender { get; set; }
public virtual tbl_Member tbl_Member { get; set; }
}
如果我编写db.tbl_Userinfo.Add(userinfo),它将在数据库中添加一条新记录。我不知道错误在哪里。
--- Class Part-
public ActionResult Edit()
{
var dataSet = Session["Users"] as tbl_Member;
var member = db.tbl_Userinfo.FirstOrDefault(m => m.fk_UserID == dataSet.UserID);
var change = new UserinfoModel();
change.UserInfoID = member.UserInfoID;
change.Adress = member.Adress;
change.DateOfBirth = member.DateOfBirth;
change.PhoneNumber = member.PhoneNumber;
change.UserImage = member.UserImage;
change.fk_UserID = member.fk_UserID;
ViewBag.fk_GenderID = new SelectList(db.tbl_Gender, "GenderID", "Gender");
return View(change);
}
[HttpPost]
public ActionResult Edit(UserinfoModel Userinfo)
{
var userinfo = new tbl_Userinfo();
userinfo.Adress = Userinfo.Adress;
userinfo.DateOfBirth = Userinfo.DateOfBirth;
userinfo.PhoneNumber = Userinfo.PhoneNumber;
userinfo.UserImage = Userinfo.UserImage;
userinfo.fk_GenderID = Userinfo.fk_GenderID;
db.SaveChanges(); /* it does not work.*/
return RedirectToAction("Show"); /* is it true?
}
}
答案 0 :(得分:0)
您需要更新附加到数据上下文的一行或添加一个新行。
我要包含“编辑”代码,因为这就是您的控制器操作所说的内容。如果要创建全新的行,则需要在调用SaveChanges()之前将记录添加到DbSet <>中。
[HttpPost]
public ActionResult Edit(UserinfoModel Userinfo)
{
var dataSet = Session["Users"] as tbl_Member;
var member = db.tbl_Userinfo.FirstOrDefault(m => m.fk_UserID == dataSet.UserID);
member.Adress = Userinfo.Adress;
member.DateOfBirth = Userinfo.DateOfBirth;
member.PhoneNumber = Userinfo.PhoneNumber;
member.UserImage = Userinfo.UserImage;
member.fk_GenderID = Userinfo.fk_GenderID;
db.SaveChanges();
return RedirectToAction("Show");
}