2012-03-31 160 views
1

我對實體框架頗爲陌生,因此我可能忽略了一些簡單的東西。實體框架:將實體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(),因爲我想這些是原子操作。

我曾希望返回類別並隨後將該類別用作新課程的屬性會將該課程鏈接到該類別,但顯然情況並非如此。如何將我的課程鏈接到數據庫中已存在的類別?

+0

您在存儲庫中使用單獨的上下文實例,對不對?否則,你的代碼會真正起作用。 – Slauma 2012-03-31 15:29:59

回答

2

我不確定你的數據模型是如何構建的,但你可以做這樣的事情。

course.CategoryId = category.CategoryId; 

這樣你映射關係中的實際外鍵,它做同樣的事情。

+0

我解決了這個問題,沒有在課程上設置Category,而只是CategoryId。這對我來說是違反直覺的,因爲在Hibernate(也許是NHibernate?)中,當你在課程中設置一個CategoryId類別的類別時,假設你想將該課程鏈接到該現有類別。但也許這就是EF如何運作!謝謝。 – Julius 2012-04-01 10:25:22

0
Category category = new Category {Name = "Test category"}; 
Course course = new Course { 
FullDescription = "This is a new course", 
    Name = "My new course", 
    Category = category 
}; 

courseRepo.AddCourse(course); 

如果您的存儲庫具有相同的上下文,則只能使用AddCourse來添加兩個實體。如果每個存儲庫都有自己的上下文,則應將類別附加到courseRepo上下文中或將實體加載到其中(但由於存在不同的存儲庫,我認爲它不適合您)。