Self relationship at EF6

Asked

Viewed 1,763 times

3

I need to make a relationship in one of the entities, as I do to reference the entity itself for both child records and 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; }
}

1 answer

5


Set your model 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 setting, 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);
}
  • It worked perfectly, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.