Foreign key problem RRS feed

  • Question

  • I have a table called Categories and a table called RelatedCategories
    RelatedCategories is used to create an association between two arbitrary rows on the the Categories table.

    So, for example, I may have a Category called milk and a category called cookies.  I may create a row on RelatedCategories that points to both rows on Categories.   Here are the classes:

    public partial class Category
            public Category()
                RelatedCategories = new HashSet<RelatedCategory>();
        	public int ID { get; set; }
        	public Nullable<int> ParentID { get; set; }
        	public string Name { get; set; }
        	public int DataProviderID { get; set; }
        	public int NativeID { get; set; }
        	public virtual ICollection<RelatedCategory> RelatedCategories { get; set; }
    	public partial class RelatedCategory
        	public int ID { get; set; }
            public int CategoryID { get; set; }
            public int RelatedCategoryID { get; set; }
            public virtual Category Category { get; set; }
        	public virtual Category CategoryThatIsRelated { get; set; }

    In OnModelCreating I have this:

    // RelatedCategories
    			mb.Entity<RelatedCategory>().HasKey(x => x.ID);
                    HasRequired(x => x.Category)
                    .WithMany(x => x.RelatedCategories)
                    .HasForeignKey(x => x.CategoryID);
                    .HasRequired(x => x.CategoryThatIsRelated); // FK is RelatedCategoryID....... how do I name it here
    My question is:  How do I tell EF the foreign key for the navigation property CategoryThatISRelated is RelatedCategoryID?

    Thursday, January 30, 2014 6:00 AM


All replies