【发布时间】:2013-04-18 20:00:01
【问题描述】:
在尝试将多个实体级别添加到我的 EF 上下文时,我收到 Object reference not set to an object of an instance 错误。
以如下三级类结构为例:
public class Forum
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Blog> Blogs { get; set; }
}
public class Blog
{
public int ID { get; set; }
public string Name { get; set; }
public int ForumID { get; set; }
public virtual Forum Forum { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
public class Post
{
public int ID { get; set; }
public string Name { get; set; }
public int BlogID { get; set; }
public virtual Blog Blog { get; set; }
}
对于给定的论坛,我想添加一个带有新帖子的新博客:
Forum MyForum = context.Forums.Find(1);
Blog MyBlog = new Blog { Name = "My New Blog" };
Post MyPost = new Post { Name = "My New Post" };
MyForum.Blogs.Add(MyBlog); // This WORKS
MyBlog.Posts.Add(MyPost); // This FAILS
context.SaveChanges(); // We never make it this far
我已经尝试了所有可能的订单组合,包括将context.SaveChanges() 紧跟在.Add(MyBlog) 之后。看起来有点窒息,因为没有 Blog.ID 可用于 Post.BlogID,但 EF 会生成临时键值以供在这种情况下使用。
有什么想法吗?
【问题讨论】:
标签: c#-4.0 asp.net-mvc-4 entity-framework-5