【问题标题】:codefirst one to one relationshipcodefirst 一对一关系
【发布时间】:2013-12-08 08:20:29
【问题描述】:

我在 asp.net 应用程序网络表单中使用 codefirst EF。我要上课:

public class Product
{

    [ScaffoldColumn(false)]
    public int ProductID { get; set; }
    public string ProductName { get; set; }        
    public virtual Picture Pic{ get; set; }

}

public class Picture
{
    [ScaffoldColumn(false)]
    [Key]
    public int PictureID { get; set; }


    public String Path { get; set; }


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

    public virtual Product Product { get; set; }
}

这些类之间的关系是一对一的。我设置了 ForeignKey 属性,但是当我运行 Update-database 时,我收到“多重性在角色中无效。因为从属角色属性不是关键属性,所以从属角色多重性的上限必须是 '*'。” 你能帮帮我吗?

【问题讨论】:

    标签: asp.net entity-framework ef-code-first


    【解决方案1】:

    What does principal end of an association means in 1:1 relationship in Entity framework

    EntityFramework 可以处理的一对一关系是两个主键之间的关系(不存在外键),其中一个实体是 Principal,另一个是 Dependent。 Dependent 是将主要实体 ID 称为其主键的对象。意味着从属的主键也是它的外键。

    在您的情况下,产品将是主体,图片将是从属。因此,ID 为 (5) 的产品的 PictureID 也是 (5)。

    这样你的类应该如下所示:

    [Table("Product")]
    public class Product
    {
        [Key, ScaffoldColumn(false)]
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public virtual Picture Pic { get; set; }
    }
    
    [Table("Picture")]
    public class Picture
    {
        [ScaffoldColumn(false)]
        [Key, ForeignKey("Product")]    // Key, and Foreign Key the refers to ProductID
        public int PictureID { get; set; }
    
        public String Path { get; set; }
    
     // public int? ProductID { get; set; } // No foreign key, and ProductID can be accessed through the Product object below
    
        public virtual Product Product { get; set; }
    }
    

    你的数据库应该是这样的:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多