Entity framework 插入后延迟加载属性

Entity framework 插入后延迟加载属性,entity-framework,Entity Framework,我有一个父对象和子对象。如果我这样做 Child c = new Child(); c.ParentID = parentID; context.Child.Add(c); context.SaveChanges(); int i = c.Parent.ParentID; // throws an exception b/c Parent is null 为什么要这样做?如果我得到一个新的上下文(保存后),我可以很好地看到父对象。我猜您正在使用启用了延迟加载的操作。如果希望在将具有外键属性

我有一个父对象和子对象。如果我这样做

Child c = new Child();

c.ParentID = parentID;
context.Child.Add(c);
context.SaveChanges();

int i = c.Parent.ParentID; // throws an exception b/c Parent is null

为什么要这样做?如果我得到一个新的上下文(保存后),我可以很好地看到父对象。

我猜您正在使用启用了延迟加载的操作。如果希望在将具有外键属性的对象添加到上下文后填充导航属性,则必须使用
DbSet
Create
方法(而不是使用
new
实例化对象):


通过主动延迟加载,这将创建一个代理对象,以确保加载导航属性。

问题之后有点晚,但只是为了澄清。正如MS docs所述,我使用以下方法:

using (var context = new BloggingContext())
{
    var post = context.Posts.Find(2);

    // Load the blog related to a given post.
    context.Entry(post).Reference(p => p.Blog).Load();

    // Load the blog related to a given post using a string.
    context.Entry(post).Reference("Blog").Load();

    var blog = context.Blogs.Find(1);

    // Load the posts related to a given blog.
    context.Entry(blog).Collection(p => p.Posts).Load();

    // Load the posts related to a given blog
    // using a string to specify the relationship.
    context.Entry(blog).Collection("Posts").Load();
}
但只有在使用Add()方法时,它才会起作用

context.Set().Add(post);
SaveChanges();
context.Entry(post.Reference)(p=>p.Blog.Load();

它不适用于.AddRange()

您是否先使用EF 4.1代码?否。我们先使用EF,但不使用代码。如果context.Child为空,您将执行的操作可能重复?在我的例子中,我正在变为null,有什么建议吗?这解释了为什么我无法导航到任何父导航属性,而我正在阅读的所有其他内容都建议它应该正常工作。谢谢。@Slauma这太好了,谢谢你。但是,如果我的子对象有一个具有必需值的构造函数,那么如何使用Create()方法呢?e、 通常我会做Child c=新的Child(其他对象o)。显然context.Child.Create(o)不起作用。@Jordan:不可能<代码>创建只能通过默认构造函数实例化实体。在调用
Create
(或调用类似
Init
的方法,将参数传递到该方法)后,必须设置实体属性。
using (var context = new BloggingContext())
{
    var post = context.Posts.Find(2);

    // Load the blog related to a given post.
    context.Entry(post).Reference(p => p.Blog).Load();

    // Load the blog related to a given post using a string.
    context.Entry(post).Reference("Blog").Load();

    var blog = context.Blogs.Find(1);

    // Load the posts related to a given blog.
    context.Entry(blog).Collection(p => p.Posts).Load();

    // Load the posts related to a given blog
    // using a string to specify the relationship.
    context.Entry(blog).Collection("Posts").Load();
}
context.Set<T>().Add(post);
context.SaveChanges();
context.Entry(post).Reference(p => p.Blog).Load();