0

It is look like same question but mine little bit different.

Entity Framework 4 CTP 5 Self Referencing Many-to-Many

sample code;

public class Category 
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Category> Parents { get; set; }
    public virtual ICollection<Category> Children { get; set; }        
}

I got right result when I define a field Parent as Category, instead of parents as List.

Category class well designed, but POCO? What should I do? Thanks in advance.

Community
  • 1
  • 1
Nuri YILMAZ
  • 4,291
  • 5
  • 37
  • 43

1 Answers1

2

Your class works fine for me without any customizations. Even the [Key] attribute is not required.

Here's some code that exercises this model:

using (var context = new MyContext())
{
    var parent1 = new Category { Name = "Parent 1" };
    var parent2 = new Category { Name = "Parent 2" };
    var child1 = new Category { Name = "Child 1" };
    var child2 = new Category { Name = "Child 2" };
    parent1.Children = new List<Category> { child1, child2 };
    parent2.Children = new List<Category> { child1, child2 };
    context.Categories.Add(parent1);
    context.Categories.Add(parent2);
    context.SaveChanges();
}
using (var context = new MyContext())
{
    var categories = context.Categories.OrderByDescending(x => x.Children.Count)
                                       .ToList();
    foreach (var category in categories)
    {
        Console.Write(category.Name + ": ");
        Console.WriteLine("Parents ({0}) Children ({1})",
            string.Join(",", category.Parents.Select(x => x.Name).ToArray()),
            string.Join(",", category.Children.Select(x => x.Name).ToArray()));
    }
}

This will print:

Parent 1: Parents () Children (Child 1,Child 2)
Parent 2: Parents () Children (Child 1,Child 2)
Child 1: Parents (Parent 1,Parent 2) Children ()
Child 2: Parents (Parent 1,Parent 2) Children ()
Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154