简体   繁体   中英

Using Data annotations to create navigation property from class to itself?

Using Entity Framework Code first I have a class that holds data for a drop-down list. The same class holds records that are sub-items for the items in the main list. Ultimately this will create a cascading set of drop-down lists.

I am trying to figure out how to make the navigation property for the class link back to itself. The issue class is the one that I am using to populate the drop-down list. The Complaint class also has a link to the Issues class but does not need a link back to the subcategory.

public class Issue
{
    public Issue()
    {
       Complaints = new List<Complaint>();
       SubIssues = new List<Issue>();
    }

    [Key]
    public int IssueID { get; set; }
    public string Name { get; set; }
    public bool IsSubCategory { get; set; }

    [ForeignKey("IssueID")]
    public ICollection<Issue> SubIssues { get; set; }

    public virtual ICollection<Complaint> Complaints { get; set; }
    }

public class Complaint
{
    public Complaint()
    {            
    }    
    public int ComplaintID { get; set; }
    public string Name {get; set;}

    [ForeignKey("IssueID")]
    public virtual Issue Issue { get; set; }         
}

I did something similar, but actually did only have a parent reference in the children. Either way this should work.

public class Folder
{
    [Key]
    public int Id { get; set; }

    // Some Property
    public string Name { get; set; }

    // They foreignkey for Many-side
    public virtual Folder Parent { get; set; }

    // The list for One-side (Not tested in my application)
    public virtual ICollection<Folder> SubFolders { get; set; }
}

It is same as a regular one-to-many relation, just all the references are within same entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM