2013-04-16 58 views
11

我試圖找到正確的語法來爲測試數據創建數據庫。我對我的產品表有一個外鍵。這是類別。我已經用類別的值爲種子數據庫播種了數據,但是一直停留在如何將該關係添加到產品上。我已經嘗試過這種方式無濟於事。使用代碼優先實體框架爲數據庫播種 - 外鍵語法

context.Categories.AddOrUpdate(x => x.Name, 
    new Category 
    { 
     Name = "Fruit" 
    }); 

context.Products.AddOrUpdate(x => x.Name, 
    new Product 
    { 
     Name = "Cherries", 
     Description = "Bing Cherries", 
     Measure = "Quart Box", 
     Price = 1.11M, 
     Category = context.Categories.FirstOrDefault(x => x.Name == "Fruit") 
    } 
}); 

任何人都可以指向正確的方向嗎?

+0

請提供產品分類。在產品類中,您必須將外鍵字段設置爲Category(Category_id)。您可以分配該category_id值。 – Saanch

回答

23

我發現爲了完成來自Category的外鍵是對上下文進行保存更改。然後我能夠查詢categoryId的上下文並將其保存到產品的CategoryId。

context.Categories.AddOrUpdate(x => x.Name, 
     new Category 
     { 
      Name = "Fruit" 
     }); 

      context.SaveChanges(); 

      context.Product.AddOrUpdate(x => x.Name, 
      new Product { 
Name = "Cherries", 
Description = "Bing Cherries", 
Measure = "Quart Box", 
Price = 1.11M, 
CategoryId = context.Categories.FirstOrDefault(x => x.Name == "Fruit").Id 
}