SimpleUser
SimpleUser

Reputation: 1351

EF 4.1 Code First - Self-referencing foreign keys and Foreign key to other tables

I have a POCO class as follows

public class Category 
{ 
   public int ID {get; set; }
   public string desc {get; set; }
   public int parentID {et; set; }
}

public class Issue 
{
   public int ID {get; set;}
   ....
   public int categoryID {get; set; }
   public int subCategoryID {get; set; }

   public virtual Category category{get; set; }
   public virtual Category subCategory {get; set;}
}

I keep getting errors with foreign keys with the above classes. Basically, my Category table holds categories with sub categories. And an issue can have a category and subCategory. Would somebody guide me to the correct way to define this relationship? I've tried using Foreign Key annotations but it gives me an error saying the data base was created but the object creation failed because of foreign key relation specified on Issue. Any ideas why? And what I can do to resolve this ?

Upvotes: 2

Views: 5276

Answers (2)

Yablargo
Yablargo

Reputation: 3596

You can do this with a single class.

For EF4.1 Code first I have the following example:

/// <summary>
/// represents a single configuration item within CM
/// </summary>
public class CI
{
    [Key]
    public int ID { get; set; }

    ....

    [ForeignKey("Parent")]
    public int? Parent_ID { get; set; }




    [InverseProperty("Parent")]
    [ForeignKey("Parent_ID")]
    public virtual ICollection<CI> Contents { get; set; }


    [InverseProperty("Contents")]
    public virtual CI Parent { get; set; }

Upvotes: 2

Paige Cook
Paige Cook

Reputation: 22555

Please see this article - How to Configure a Self Referencing Entity in Code First

I believe that will help you setup the relationship correctly. As you will see in the article you need to define some addditional fluent settings in the OnModelCreating method in your DbContext class.

Upvotes: 4

Related Questions