【问题标题】:Table Relations with as property Entity VS as property ID以属性实体 VS 作为属性 ID 的表关系
【发布时间】:2022-01-11 11:26:48
【问题描述】:

我正在观看“CODE FIRST ENTITY FRAMEWORK CORE”的教程我有 2 个问题;

  1. 我需要使用 [ForeignKey] 属性吗?我应该把它放在哪里,在产品实体中还是在类别实体中(一对一、一对多等都无所谓)
  2. 为什么没有 [DefaultValue] 属性?
  3. 关于关系,一些教程显示了这种方式
namespace EntityExample
{
   public class Product
   {  
      public int ProductId { get; set; }

      public Category Category { get; set; }
   }

   public class Category
   {
      public int CategoryId { get; set; }
    
      public ICollection<Product> Products { get; set; }
   }
}

但其他人喜欢使用它

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

      public int CategoryId { get; set; }
   }

   public class Category
   {
      public int CategoryId { get; set; }
    
      public ICollection<int> ProductId { get; set; }
   }
}

哪个是正确的?

【问题讨论】:

标签: asp.net-mvc entity-framework entity-framework-core data-annotations table-relationships


【解决方案1】:

您好,欢迎来到 Stack Overflow。您的问题非常接近寻求意见,这里是not allowed

为了帮助你远离意见,我建议你创建一个有两个表和外键的数据库;然后搭建模型。您将看到 Microsoft 的建议。

您展示的示例都不正确(尽管第一个更好)。我很确定没有教程会显示第二个示例 - 但我也进入了意见领域。

【讨论】:

    猜你喜欢
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多