这是可能的,但你必须使用跟踪代理。为此,请修改Category类,以便
持久化属性是虚拟的。
public class Category
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Category Parent { get; set; }
public virtual ICollection<Category> Children { get; set; }
}
using (var context = new ObjectContext(connectionString))
{
// This should be default value
context.ContextOptions.ProxyCreationEnabled = true;
var cat0 = context.CreateObject<Category>();
cat0.Name = "A";
var cat1 = context.CreateObject<Category>();
cat1.Name = "B";
cat1.Parent = cat0;
context.CreateObjectSet<Category>().AddObject(cat0);
context.SaveChanges();
}
编辑:
如果您不喜欢跟踪代理(需要现有上下文)的方法,您可以反转创建实体的方式。不必在childs上设置Parent属性,而必须在Parent上填充childs。那样的话就行了。