用Code First Entity Framework填充数据库 - 外键语法

15

我正在尝试找到正确的语法来用测试数据填充数据库。我的产品表有一个指向外键,它是类别。我已经为类别的值填充了数据库,但是不知道如何将其关联到产品。我已经尝试过以下方式,但均无效。

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

有人能指引我正确的方向吗?


请提供Product类。在Product类中,您必须拥有指向Category的外键字段(Category_id)。您可以分配该category_id值。 - Saanch
1个回答

28

我发现实现从分类(Category)的外键是要对上下文(context)进行保存更改。然后我可以查询上下文中的categoryId并将其保存到产品(Product)的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
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接