2011-04-20 60 views
0

它看起來像同樣的問題,但我的一點點不同。POCO自引用多對多

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

我得到正確的結果,當我定義一個字段父類爲類,而不是父母作爲列表。

類別設計良好,但POCO?我該怎麼辦?提前致謝。

+0

什麼問題,你有什麼呢?你真的還在使用CTP5嗎?它已經過時了,你應該更新到EF 4.1(http://blogs.msdn.com/b/adonet/archive/2011/04/11/ef-4-1-released.aspx) – Slauma 2011-04-20 17:15:16

+0

類別實際上可以有多個*父母? – 2011-04-20 18:07:35

+0

@Slauma:對不起EF 4.1,我已經改變了問題。 – 2011-04-21 14:16:11

回答

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

非常感謝。這是工作。當我檢查Sql Server時,我犯了錯誤。我永遠不會再看它:) – 2011-04-22 08:28:46