我對實體框架頗爲陌生,因此我可能忽略了一些簡單的東西。實體框架:將實體A鏈接到現有實體B
在我的控制器類中,我將一個新的Category實體添加到數據庫,接下來我將該實體用作Course實體的一個屬性。當我保存課程實體時,該類別再次保存到數據庫,而我希望新課程將引用已插入的類別。
,節省了第一類(簡體)控制器代碼:
// Create and save the category
Category category = new Category {Name = "Test category"};
category = context.Categories.Add(category);
context.SaveChanges(); // The category object now has a CategoryId (the pk of the record)
// Create and save the course
Course course = new Course {
FullDescription = "This is a new course",
Name = "My new course",
Category = category // Hoping this will have EF make a link to the just inserted category
};
context.Courses.Add(course);
context.SaveChanges(); // Saves the Course AND creates a **new** Category in the db
這個問題似乎是我的SaveChanges調用()的兩倍。什麼工作是刪除第一個調用context.saveChanges(),但是,這不是我的實際代碼。在我的應用程序中,我使用存儲庫模式,並通過調用categoryRepository.AddCategory(Category category)來添加類別。保存課程的方式完全相同,只需調用courseRepo.AddCourse(課程課程),其中也包含對saveChanges()的調用。
public Category AddCategory(Category category)
{
category = context.Categories.Add(category);
context.SaveChanges();
return category;
}
我不想刪除對的SaveChanges()調用在AddCourse()和AddCategory(),因爲我想這些是原子操作。
我曾希望返回類別並隨後將該類別用作新課程的屬性會將該課程鏈接到該類別,但顯然情況並非如此。如何將我的課程鏈接到數據庫中已存在的類別?
您在存儲庫中使用單獨的上下文實例,對不對?否則,你的代碼會真正起作用。 – Slauma 2012-03-31 15:29:59