5

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?

1
  • Do you mean using Code First approach or other? May 23, 2012 at 10:20

2 Answers 2

5

I think the following shall do it:

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

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.