【发布时间】:2013-01-13 20:31:29
【问题描述】:
我想在断开连接(从上下文)模式下使用实体框架 POCO。在我的场景中,我正在创建一个新的父对象,并希望将现有的子对象附加到它,然后将其保存到数据库中。
下面的代码在保存新的学生记录时插入了新的课程记录,而我希望将现有的课程记录链接到新的学生记录。
如何在实体框架中执行此操作...
- 对象可以从上下文中断开。 (即在一个上下文中查询,然后在另一个上下文中保存)
- 我不需要从数据库中重新查询子记录,这样我就可以在保存到数据库时将它附加到父记录。当我已经将它作为内存中的对象时,我真的想避免对数据库进行额外的访问。
这个页面展示了一个数据库图,下面的代码是基于http://entityframeworktutorial.net/EF4_EnvSetup.aspx#.UPMZ4m-UN9Y的
class Program
{
static void Main(string[] args)
{
//get existing course from db as disconnected object
var course = Program.getCourse();
//create new student
var stud = new Student();
stud.StudentName = "bob";
//assign existing course to the student
stud.Courses.Add(course);
//save student to db
using (SchoolDBEntities ctx = new SchoolDBEntities())
{
ctx.Students.AddObject(stud);
ctx.SaveChanges();
}
}
static Course getCourse()
{
Course returnCourse = null;
using (var ctx = new SchoolDBEntities())
{
ctx.ContextOptions.LazyLoadingEnabled = false;
returnCourse = (from s in ctx.Courses
select s).SingleOrDefault();
}
return returnCourse;
}
}
【问题讨论】:
标签: c# .net entity-framework