1

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?

2
  • This is a question that is purely about Entity Framework code-first. It has nothing what at all to do with MVC3. The fact that you are using it in an MVC3 project is irrelevant. Commented Aug 11, 2011 at 12:00
  • I think that's what the virtual property you defined in the entity will do. Commented Aug 11, 2011 at 12:11

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks it was [ForeignKey("S2_Product")] not [ForeignKey("S2_Products")] no 's' i think it worked!
Try changing the attribute to [ForiegnKey("S2_Product")] to match the property name rather than the entity name.
Oops. I didn't see you last comment as I was entering mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.