EF保存外键,提示违反唯一性

应该通过上下午对象来保存数据,而不是创建一个新的对象

 

using (var dc = new SchoolContext())
            {
                //GRADE g = new GRADE() { GradeId=2 };
                var greadeinfo = dc.Grades.Find(2);
                STUDENT stu = new STUDENT() { STUDENTID = 3, STUDENTNAME = "李四", HEIGHT = 180.5F, WEIGHT = 140.5F, DATEOFBIRTH = DateTime.Now, PHOTO = "987654321", GRADE= greadeinfo };

                //dc.Grades.Add(g);
                dc.Students.Add(stu);
                dc.SaveChanges();

                MessageBox.Show("创建成功");
            }

  

posted @ 2022-01-06 19:55  zq爱生活爱代码  阅读(49)  评论(0编辑  收藏  举报