POCO自我引用了很多对很多

时间:2011-04-20 14:45:44

标签: ef-code-first entity-framework-ctp5

看起来像是同样的问题但是我的一点点不同。

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

示例代码;

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

当我将字段Parent定义为Category而不是Parent作为List时,我得到了正确的结果。

类别设计精良,但POCO?我该怎么办?提前谢谢。

1 个答案:

答案 0 :(得分:2)

没有任何自定义,您的课程对我来说很好。即使是[Key]属性也不是必需的。

以下是一些练习此模型的代码:

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

这将打印:

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