简体   繁体   中英

Foreign Key relationship in Entity Framework

I am new to entity framework. I have two tables...

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; }

}

and

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

The S7_ProductID should refer to the S2_ProductID?

If I understand your question and what you are tryiing to do. I think you want to add the ForiegnKey attribute to the S7_ProductID property.

As shown here:

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; }

}

You might also need to add something like the following in the OnModelChange method of the model:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM