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("创建成功"); }