0
votes

I have an entity with a Property called ParentId linked to an navigation property called Parent. This relationship seems to be working fine but my issue is now i want to have another navigation property which would be a list of "Child" items where the parent is the same as the entities ID.

I have Tried "ID", "Parent" in my FK attribute but i get the "The ForeignKeyAttribute on property 'Children' on type 'jrSite.Core.SiteModel' is not valid" error.

How do i tell EF that i want that navigation property to search the SiteModel table for items with matching parent id?

My class is below

public class SiteModel
{
    public SiteModel() { }
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public DateTime Created { get; set; }

    [ForeignKey("Creator")]
    public int CreatorID;
    public SiteAccount Creator { get; set; }

    [ForeignKey("Owner")]
    public int OwnerID;
    public SiteAccount Owner { get; set; }

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

    [ForeignKey("Parent")]
    public List<SiteModel> Children { get; set; }

    public SiteModel(SiteAccount creator, SiteAccount owner)
    {
        Creator = creator;
        Owner = owner;
        Created = DateTime.Now;
    }
}
2
you don't need the construct here: public SiteModel() { }. It's by default anyway. - Yair Nevet

2 Answers

0
votes

Override OnModelCreating in your DBContext class and add this code:

modelBuilder.Entity<SiteModel>()
  .HasRequired<SiteAccount>(s => s.Creator);


modelBuilder.Entity<SiteModel>()
  .HasRequired<SiteAccount>(s => s.Owner);
0
votes

The ParentID/Parent nav property will take care of this relationship already - get rid of the ForeignKey attribute on the Children property declaration. I just tested the following and it works:

public class HierarchicalEntity
{
    public int Id { get; set; }
    public string Description { get; set; }

    public int? ParentId { get; set; }
    public virtual HierarchicalEntity Parent { get; set; }

    public virtual ICollection<HierarchicalEntity> Children { get; set; }
}


        using (var db = new TestEntities())
        {
            var parent = new HierarchicalEntity();
            db.HierarchicalEntity.Add(parent);

            var children = new List<HierarchicalEntity>()
            {
                new HierarchicalEntity() { Parent = parent },
                new HierarchicalEntity() { Parent = parent }
            };

            children.ForEach(c => db.HierarchicalEntity.Add(c));

            db.SaveChanges();
        }