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 S开发者_运维技巧2_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);
精彩评论