在数据库中插入一行并使用相同的操作方法asp.net mvc更新它

时间:2018-04-08 17:10:41

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

如何在数据库中插入一行并使用相同的操作方法更新它我编写此代码但它没有更新?

if (ModelState.IsValid)
            {
                db.Users.Add(reg.users);
                db.Idea.Add(reg.idea);
                db.Students.Add(reg.students[0]);
                db.SaveChanges();

                int max1 = db.Users.Max(p => p.UserId);
            int max22 = db.Idea.Max(d => d.IdeaId);
            int max33 = db.Students.Max(c => c.StudentID);

            var result = db.Students.SingleOrDefault(x => x.StudentID == max33);
            result.UserId = max1;
            result.IdeaId = max22;

            db.SaveChanges();
                return View("RegisterLeaderPost");


            } 

这是学生模特 我想更新外键             public int UserId

        public int? IdeaId

我没有得到任何错误,但是空值没有更新

 public class StudentsModel
    {
        [Key]
        [Display(Name ="ID")]
        public int StudentID { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]//20150090
        public string student_ID { get; set; }

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

        [Required]
        [Display(Name = "Gpa")]
        [Range(1.00, 4.00, ErrorMessage = "It must be in range 0.00 to 4.00 :)")]
        public float Gpa { get; set; }

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

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

        [ForeignKey("UserId")]
        public int UserId;
        public UsersModel Users { get; set; }

        [ForeignKey("IdeaId")]
        public int? IdeaId;
        public IdeaModel Idea { get; set; }


    }

2 个答案:

答案 0 :(得分:0)

您似乎正在使用Entity Framework(我的错误,我认为您使用的是Entity Framework的Core版本),如果这是正确的,那么我可能会建议做这样的事情:

   db.Update(result);
   db.SaveChanges();

以下是对该代码的引用:

Modifying data via the DbContext

答案 1 :(得分:0)

将实体添加到其集合中,例如将user添加到Users,它将返回此实体的对象,您可以在SaveChanges之后使用它,因为它将包含新ID

if (ModelState.IsValid)
{
    var user = db.Users.Add(reg.users);
    var idea = db.Idea.Add(reg.idea);
    var student = db.Students.Add(reg.students[0]);
    db.SaveChanges();

    student.UserId = user.UserId;
    student.IdeaId = idea.IdeaId;

    db.SaveChanges();
    return View("RegisterLeaderPost");
}