我想在斷開(從上下文)模式下使用實體框架POCO。在我的場景中,我創建了一個新的Parent對象,並希望將現有的子對象附加到它,然後將其保存到數據庫。
下面的代碼會在保存新學生記錄時插入新課程記錄,而不希望將現有課程記錄鏈接到新學生記錄。實體框架:將現有的子POCO添加到新的父POCO,在DB中創建新的子節點
我怎樣才能在實體框架在那裏......
- 的對象可以從上下文斷開做到這一點。 (即在一個上下文中查詢,然後保存在不同的上下文中)
- 我不需要重新從數據庫中查詢子記錄,所以我可以在保存到數據庫時將它附加到父級。當我已經將它作爲內存中的一個對象時,我真的想要避免額外訪問數據庫。
此頁面顯示下面的代碼是基於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;
}
}
第二個選項幾乎可行,但我得到一個「該對象無法連接,因爲它已經在對象上下文中。」 「ctx.Students.AddObject(stud)」錯誤;「線。我假設在做「stud.Courses.Add(course)」的時候,我無法做到這一點;「在它之前。我想仍然在柱頭物體中使用課程系列。 – MakkyNZ
那麼,我沒有一個方便測試的解決方案,但是先嚐試附加它,然後將其添加到學生。希望這種方式不會被EF標記爲「已添加」。 –
這不是很理想。我希望首先在對象級別發生父 - >子關係,因爲它可能尚未準備好保存到數據庫。也許我應該刪除EF生成的實體之間的所有關係,並手動控制它自己? – MakkyNZ