实体框架中的外键关系

时间:2011-08-11 11:57:01

标签: c# entity-framework

我是实体框架的新手。我有两张桌子......

public class S7_Baskets
{
    [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    [Column(Order = 0)]
    public string S7_BasketID { get; set; }
    [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    [Column(Order = 1)]
    public int S7_Seqno { get; set; }
    public int S7_ProductID { get; set; }

    public virtual S2_Products S2_Product { get; set; }

}

public class S2_Products
{
    [Key]
    public int S2_ProductID { get; set; }
    public string S2_Desc { get; set; }
}

S7_ProductID应该参考S2_ProductID?

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题以及你正在尝试做什么。我想您要将ForiegnKey属性添加到S7_ProductID属性。

如下所示:

public class S7_Baskets
{
   [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
   [Column(Order = 0)]
   public string S7_BasketID { get; set; }

   [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
   [Column(Order = 1)]
   public int S7_Seqno { get; set; }

   [ForeignKey("S2_Products")]
   public int S7_ProductID { get; set; }
   public virtual S2_Products S2_Product { get; set; }

}

您可能还需要在模型的OnModelChange方法中添加以下内容:

modelBuilder.Entity<S7_Baskets>()
            .HasRequired(t => t.S2_Products)
            .WithMany()
            .HasForeignKey(t => t.S7_ProductID).WillCascadeOnDelete(false);