EF 5 One to Many Self References - Code First

I have read several one to many posts about myself but have seen my particular permutation. If I missed it please post the link.

Here's my scenario. I have two tables. A function contains a collection of Epics, and an Epic can contain a collection of child epics recursively (I can have child (n) epic children).

Below is a simple outline of the type of models I am looking for to create.

public class Feature
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Epic> Epics { get; set; } 
}

public class Epic
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int FeatureId { get; set; }

    public int ParentEpicId { get; set; }
    public virtual ICollection<Epic> ChildEpics { get; set; } 
}

      

I can almost specify the relationship in the modelBuilder, but depend on one thing. The first epic collection will have a FeatureId FK back to the parent function and a null ParentEpicId, but all levels of epic collections below this will have the FeatureId set to null and the ParentEpicId the ID of the parent epic. (The FeatureId can point to the top-level element of the epic children tree, but this is optional)

How can I first specify this type of relationship in EF code?

If you don't understand or need more information, please let me know.

+3


source to share


1 answer


Since it is obvious that both FeatureId

and ParentEpicId

are displayed in columns with a null value in the database, they should be compared with zero properties in the data model. You must change your class Epic

to:

public class Epic
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int? FeatureId { get; set; }

    public int? ParentEpicId { get; set; }
    public virtual ICollection<Epic> ChildEpics { get; set; } 
}

      



As far as requiring only one of the FeatureId and ParentEpicId to be set, I don't think EF has such a mechanism out of the box.

+3


source







All Articles