Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seeding a Database with Code First Entity Framework - Foreign key syntax

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?

like image 568
Jeff Pearce Avatar asked Apr 16 '13 07:04

Jeff Pearce


People also ask

How do I add a foreign key in code first approach in Entity Framework?

To create Foreign Key, you need to use ForeignKey attribute with specifying the name of the property as parameter. You also need to specify the name of the table which is going to participate in relationship.

How do you set a foreign key in an entity?

The [ForeignKey(name)] attribute can be applied in three ways: [ForeignKey(NavigationPropertyName)] on the foreign key scalar property in the dependent entity. [ForeignKey(ForeignKeyPropertyName)] on the related reference navigation property in the dependent entity.


1 Answers

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
    });
like image 158
Jeff Pearce Avatar answered Oct 09 '22 23:10

Jeff Pearce