2011-08-25 182 views
0

我有兩個表類別和產品,我想插入產品的類別。這些表格之間的表格關係是一對一的關係。C# - 實體框架插入

分類表:

CID : integer, 
CategoryName : varchar, 

產品表:

CID: integer, // foreign key to category table. 
ProductName: varchar, 
UnitsInstock: integer, 

我怎麼能寫插入一個產品進入的productTable一個簡單的查詢?我如何處理公司的關鍵情況?如果分類標識不存在,則不應插入該產品。

我會非常感謝任何形式的幫助。

+0

你使用什麼數據庫軟件?如果你設置正確,SQL Server已經爲你檢查了。 – LueTm

+0

@LueTm - Iam使用Sql Server。我需要知道的是如何編寫實體查詢以將產品插入到產品表中,但前提是產品ID與類別ID匹配。 – Erik

回答

0

一種方法可以是這一個:

int categoryIdOfNewProduct = 123; 
using (var context = new MyContext()) 
{ 
    bool categoryExists = context.Categories 
     .Any(c => c.Id == categoryIdOfNewProduct); 

    if (categoryExists) 
    { 
     var newProduct = new Product 
     { 
      Name = "New Product", 
      CategoryId = categoryIdOfNewProduct, 
      // other properties 
     }; 

     context.Products.Add(newProduct); // EF 4.1 
     context.SaveChanges(); 
    } 
    else 
    { 
     //Perhaps some message to user that category doesn't exist? Or Log entry? 
    } 
} 

它假設您的Product實體上有一個外鍵屬性CategoryId。如果你沒有一個請指出更多的細節。

+0

謝謝,這讓我很開心:D – Erik