Jef*_*rce 14 entity-framework code-first seeding
我试图找到正确的语法来种植具有测试数据的数据库.我的产品表有一个外键.这是类别.我已经在数据库中播放了类别的值,但仍坚持如何将该关系添加到产品中.我试过这种方式无济于事.
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")
}
});
Run Code Online (Sandbox Code Playgroud)
谁能指出我正确的方向?
Jef*_*rce 27
我发现,为了从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
});
Run Code Online (Sandbox Code Playgroud)