开发者

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; 开发者_如何学Goset; }
}

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 ?


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜