【发布时间】:2013-11-29 02:31:10
【问题描述】:
我正在使用 EF 6.0 和代码优先方法。
我在通过实体框架在 db 中创建和更新数据时遇到问题。我不确定在存储学生之前是否需要制作db.Groups.Attach(student.Group)。保存学生后没有这个,我也有同名但其他 GroupId 的新组。
此外,我无法更新学生,因为我遇到异常:The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
public class Student {
[Key]
public int StudentId {get; set;}
public string Name {get; set;}
public Group Group {get; set;}
}
public class Group {
[Key]
public int GroupId{ get; set;}
public string Name {get; set;}
public virtual ICollection<Student> Students {get; set;}
}
.
public class StudentDao {
public void createStudent(Student student) {
using (var db = new StorageContext()) {
// without this also creates new Group.
db.Groups.Attach(student.Group);
db.Students.Add(student);
db.SaveChanges();
}
}
public void updateStudent(Student student) {
using (var db = new StorageContext()) {
var original = db.Students.Find(student.StudentId);
if (original != null) {
original.Name = student.Name;
original.Group = student.Group;
db.SaveChanges(); //exception
}
}
}
}
【问题讨论】:
标签: c# wpf entity-framework