2

我有使用模型優先方法創建的模型。當我嘗試使用上下文訪問Book實體時,它不在那裏列出;但銷售項目已列出。爲了將Book實體添加到上下文中需要做什麼修改?EF模型優先:子類對象不出現在上下文中

注意:請閱讀Adding reference to entity causing ExceptionEntity Framework: Get Subclass objects in Repository瞭解更多詳情。

enter image description here

型號

enter image description here

代碼

enter image description here

static void Main(string[] args) 
    { 
     string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30"; 
     using (var db = new MyModelFirstTestContainer(connectionstring)) 
     { 
      Book book = new Book(); 
      book.AvailabilityStatus = "Available"; 
      book.Price = 100; 
      book.Title = "World visit"; 

      //db. 


     } 

回答

2

實體框架不會爲您的上下文中的繼承項目創建單獨的ObjectSet。如果你想添加一個繼承的實體,您將使用父對象集

from b in db.SellingItems.OfType<Book>() 
where b.Title = "my title" 
select b; 

這裏是OfType

MSDN文檔:

相反,你可以使用OfType<T>()方法是這樣的。

Book b = ...; 
db.SellingItems.Add(b); 
db.SaveChanges(); 
+1

我編輯了我的答案以顯示如何添加項目 – 2012-07-27 10:06:28

+0

請閱讀http://stackoverflow.com/questions/11686727/adding-reference-to-entity-causing-exception瞭解更多詳細信息。 – Lijo 2012-07-27 13:58:11

1

我不知道你怎麼可以添加他們那裏,但你真的想要的無論如何?

相反,我會使用「db.SellingItems.OfType()」。這樣你就可以請求所有的書籍並且已經完成了它們。如果您調用db.SellingItems,那麼您將獲得具有適當實例的所有SellingItem。

+0

簡單的繼承,就像Wouter de Kort在他的例子中顯示的那樣。 :) – Martin1921 2012-07-27 10:07:44

相關問題