【问题标题】:MVC 4 EF5 - Add sub-entities errorMVC 4 EF5 - 添加子实体错误
【发布时间】: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


    【解决方案1】:

    可以在以下位置找到答案(和根本问题)的提示:

    “简单”的解决方案是手动初始化 Blog.Posts 集合:

    Blog MyBlog = new Blog { Name = "My New Post", Posts = new List<Post>() };
    

    或者,您可以按照 Ladislav 在第二个链接中的建议将此逻辑构建到类构造函数中。

    基本上,当您创建一个新对象时,该集合为空且未初始化为 List,因此 .Add() 调用失败。 Forum.Blogs 集合能够延迟加载,因为它派生自数据库上下文。但是,Blog.Posts 是从头开始创建的,EF 无法帮助您,因此该集合默认为 null。

    【讨论】:

      猜你喜欢
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 2011-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多