Link to the same table with Entity Framework

How can I specify realtionship in the same table using Entity Framework?

My items table has the following fields: - Id (uniqueidentifier) ​​- ThreadId (uniqueidentifier) ​​- Created (datetime) - Text (nvarchar (max))

My Model Subject: - Id (Guid) - ThreadId (Guid) - Created (DateTime) - Text (string) - ChildItems (Icollection)

How to create a relationship so that ChildItems elements retain elements with Id = ThreadId?

+5
source share
2 answers

I think this will do the following:

modelBuilder.Entity<Item>()
                    .HasOptional(c => c.ChildItems)
                    .WithMany()
                    .HasForeignKey(c => c.ThreadId);
+5
source

Item Object

public class Item
{
    public Guid Id { get; set; }
    public Guid ThreadId { get; set; }
    public ICollection<Item> ChildItems { get; set; }

    /* Other properties */
}

And smooth configuration

modelBuilder.Entity<Item>()
                .HasMany(i => i.ChildItems)
                .WithOptional()
                .HasForeignKey(i => i.ThreadId);
+2
source

All Articles