Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relationship on same table with Entity Framework

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

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

My model 'Item': - Id (Guid) - ThreadId (Guid) - Created (DateTime) - Text (string) - ChildItems (Icollection)

How can I create the relationship so that ChildItems holds the items with Id = ThreadId?

like image 287
Kulvis Avatar asked May 23 '12 10:05

Kulvis


2 Answers

I think the following shall do it:

modelBuilder.Entity<Item>()
                    .HasOptional(c => c.ChildItems)
                    .WithMany()
                    .HasForeignKey(c => c.ThreadId);
like image 152
daryal Avatar answered Sep 18 '22 17:09

daryal


The Item entity

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

    /* Other properties */
}

And the fluent configuration

modelBuilder.Entity<Item>()
                .HasMany(i => i.ChildItems)
                .WithOptional()
                .HasForeignKey(i => i.ThreadId);
like image 34
Juraj Suchár Avatar answered Sep 19 '22 17:09

Juraj Suchár