15

I am trying to find the correct syntax to seed a database with test data. I have a foreign key to my product table. It is the category. I have seeded the database with the values for categories, but stuck on how to add that relationship to the product. I have tried this way to no avail.

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")
    }
});

Can anyone point me in the right direction?

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Jeff Pearce
  • 581
  • 7
  • 15
  • Please provide the Product class. In the product class you must be having the foreign key field to Category(Category_id) . You can assign that category_id value. – Saanch Apr 16 '13 at 07:15

1 Answers1

28

I found that in order to accomplish the foreign key from Category is to do a save changes to the context. Then I was able to query the context for the categoryId and save it to the CategoryId on the product.

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
    });
andreikashin
  • 1,528
  • 3
  • 14
  • 21
Jeff Pearce
  • 581
  • 7
  • 15