1

我有几个模型和一个数据库,但没有将任何东西链接在一起的外键。这似乎是我项目中的一个巨大弱点,所以我试图将外键插入我的模型中,然后可能会根据我的模型重新生成我的数据库。

我在理解外键如何工作时遇到了一些麻烦,尤其是在一对多的关系中。

对于这个例子,我有一个或多个产品,每个产品可能有多个评论:

我删除了一些注释和属性来压缩模型。

产品型号/实体:

public class Product
    {
        public int ProductId { get; set; }

        public int OwnerId {get; set; }

        public string Title { get; set; }

        public int Rating { get; set; }

        public decimal Price { get; set; }

        public int Quantity { get; set; }

        public string Description { get; set; }
    }

审查模型/实体:

 public class Review
    {

        public int ReviewId { get; set; }

        public int ProductId { get; set; }

        public int WriterId { get; set; }

        public string Title { get; set; }

        public string Body { get; set; }
    }

我想要对 ProductId 的 ProductId 到 Review 的 ProductId 的外键约束。我将如何进行这项工作?

4

2 回答 2

4

您至少需要一个导航属性来定义两个实体之间的关系,例如:

public class Review
{
    public int ReviewId { get; set; }

    [ForeignKey("Product")]
    public int ProductId { get; set; }
    public Product Product { get; set; }

    public int WriterId { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
}

如果需要,您还可以添加集合属性Product

public ICollection<Review> Reviews { get; set; }

[ForeignKey]您可以使用 Fluent API 定义 FK,而不是使用属性:

modelBuilder.Entity<Review>()
    .HasRequired(r => r.Product)
    .WithMany()  // or .WithMany(p => p.Reviews)
    .HasForeignKey(r => r.ProductId);
于 2012-05-07T18:47:22.823 回答
0

外键的目的是将表链接在一起。例如,当有唯一的 ID 号时,外键很容易解释。productId 应该是唯一的 id,并且可能是您的产品表的主键。在审查表中,productId 是一个外键,因为它将允许连接表并查看两个表中所有类别的数据。

从 Product 中选择 ProductId、Title、Price、WriterId、Description 作为 P,Review 作为 R 其中 P.ProductId = R.ProductId;

当这个 select 语句对你的 db 运行时,你会从评论表中看到产品唯一 ID、标题、价格、作者 ID、描述。关键行是 P.ProductId = R.ProductId

还要确保外键不为空

于 2012-05-07T17:47:16.697 回答