你的課程沒有任何定製,對我來說工作得很好。即使是[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()
什麼問題,你有什麼呢?你真的還在使用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
類別實際上可以有多個*父母? – 2011-04-20 18:07:35
@Slauma:對不起EF 4.1,我已經改變了問題。 – 2011-04-21 14:16:11