代码首先是一对一的关系

时间:2013-12-08 08:20:30

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

我在asp.net应用程序webforms中使用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时,我收到“Multiplicity在Role中无效。因为Dependent Role属性不是关键属性,所以Dependent Role的多重性的上限必须是'*'。” 你可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

  

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

EntityFramework可以处理的一对一关系是两个主键之间的关系(不存在外键),其中一个实体是Principal,另一个是Dependent。 Dependent是将Princial实体Id称为其主键的那个。表示Dependent的主键也是其外键。

在您的情况下,产品将是Principal,而Picture将是Dependent。因此,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; }
}

,您的数据库应如下所示:

One-to-one relationship

相关问题