Entity framework 4 实体框架代码优先-是否可以让EF自动初始化子实体集合?

Entity framework 4 实体框架代码优先-是否可以让EF自动初始化子实体集合?,entity-framework-4,ef-code-first,Entity Framework 4,Ef Code First,假设我的模型中有这些: public class Foo { public virtual Guid Id {get; set; } public virtual ICollection<Bar> Bars { get; set; } } public class Bar { public virtual Guid Id {get; set; } public virtual Guid FooId {get; set; } public virtual Foo Foo {g

假设我的模型中有这些:

public class Foo {
 public virtual Guid Id {get; set; }
 public virtual ICollection<Bar> Bars { get; set; }
}
public class Bar {
 public virtual Guid Id {get; set; }
 public virtual Guid FooId {get; set; }
 public virtual Foo Foo {get; set; }
}

我知道我可以自己初始化集合(无论是在Foo的构造函数中还是在我创建集合时,但我想知道是否有任何方法可以让EF来完成它。

框架没有提供任何现成的方法。您必须为此编写自己的方法

public class FooService
{
    ......

    Public Foo Create()
    {
        var foo = dbContext.Foos.Create();
        foo.Bars.Add(new Bar());

        return foo;
    }

    .......
}

框架没有为此提供任何现成的方法。您必须为此编写自己的方法

public class FooService
{
    ......

    Public Foo Create()
    {
        var foo = dbContext.Foos.Create();
        foo.Bars.Add(new Bar());

        return foo;
    }

    .......
}

我可以告诉你,当我第一次使用EF4.1数据库时,它只是在Foo的构造函数中做了Bars=new HashSet()的等价物,所以我怀疑你必须在构造函数中自己做。我可以告诉你,当我第一次使用EF4.1数据库时,它只是做了Bars=new HashSet()的等价物;在Foo的构造函数中,所以我怀疑您必须自己在构造函数中进行。在您的代码中,您是否使用Foo.bar而不将其分配给a,这会导致空引用异常?在您的代码中,您是否使用Foo.bar而不将其分配给a,这会导致空引用异常?