Self-relationship in EF6

3

I need to do a self-relationship in one of the entities, how do I reference the entity itself for both child records and the parent record?

public class Comentario
{
    public int IdComentario { get; set; }
    public int? IdComentarioPai { get; set; }
    public string Texto { get; set; }
    public DateTime Data { get; set; }
    public ICollection<Comentario> Respostas { get; set; }
    public Comentario ComentarioPai { get; set; }
}
    
asked by anonymous 10.04.2014 / 15:10

1 answer

5

Set your template class to the following:

public class Comentario
{
    [Key]
    public int ComentarioId { get; set; }
    public int? ComentarioPaiId { get; set; }

    public string Texto { get; set; }
    public DateTime Data { get; set; }

    public virtual Comentario ComentarioPai { get; set; }

    public virtual ICollection<Comentario> Respostas { get; set; }
}

In the context configuration, add also:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Comentario>()
        .Property(c => c.ComentarioPaiId).IsOptional();
        .HasMany(c => c.Respostas).WithOptional(c => c.ComentarioPai).HasForeignKey(c => c.ComentarioId);
}
    
10.04.2014 / 15:41