EntityFramework 学习 一 Disconnected Entities
如何把断开的实体添加到新的context上下文中
1.首先,我们需要把实体附加到新的context上下文实例中。
2.其次,手动的给实体设置适当的实体状态,因为新的context上下文不知道断开的实体上有什么操作。
DbSet.Add():
把实体添加到context上下文,并自动设置实体的属性为added状态
//disconnected entity graph Student disconnectedStudent = new Student() { StudentName = "New Student" }; disconnectedStudent.StudentAddress = new StudentAddress() { Address1 = "Address", City = "City1" }; using (var ctx = new SchoolDBEntities()) { //add disconnected Student entity graph to new context instance - ctx ctx.Students.Add(disconnectedStudent); // get DbEntityEntry instance to check the EntityState of specified entity var studentEntry = ctx.Entry(disconnectedStudent); var addressEntry = ctx.Entry(disconnectedStudent.StudentAddress); Console.WriteLine("Student EntityState: {0}",studentEntry.State); Console.WriteLine("StudentAddress EntityState: {0}",addressEntry.State); }
DbSet.Attach():
把实体添加到context中,并设置为Unchanged状态
//disconnected entity graph Student disconnectedStudent = new Student() { StudentName = "New Student" }; disconnectedStudent.StudentAddress = new StudentAddress() { Address1 = "Address", City = "City1" }; using (var ctx = new SchoolDBEntities()) { //attach disconnected Student entity graph to new context instance - ctx ctx.Students.Attach(disconnectedStudent); // get DbEntityEntry instance to check the EntityState of specified entity var studentEntry = ctx.Entry(disconnectedStudent); var addressEntry = ctx.Entry(disconnectedStudent.StudentAddress); Console.WriteLine("Student EntityState: {0}",studentEntry.State); Console.WriteLine("StudentAddress EntityState: {0}",addressEntry.State); }
通过DBContext.Entry()方法获取指定实体的状态,
DbContext.Entry(disconnectedEntity).state = EntityState.Added/Modified/Deleted/Unchanged
Parent Entity State | Entity State of child entities |
---|---|
Added | Added |
Modified | Unchanged |
Deleted | All child entities will be null |