EF7不保存对象图

时间:2015-08-25 14:38:59

标签: entity-framework-core

我希望当我找到答案时,我会觉得自己像个白痴,但我无法弄清楚为什么EF7没有像我习惯在EF6中使用它一样保存对象图。< / p>

我的背景是:

public class BloggingContext : DbContext, IBloggingContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Make Blog.Url required
        modelBuilder.Entity<Blog>()
            .Property(b => b.Url)
            .Required();

        modelBuilder.Entity<Post>()
            .Reference(p => p.Blog)
            .InverseCollection(b => b.Posts)
            .ForeignKey(p => p.BlogId);
    }
}

public class Blog
{
    private ICollection<Post> _posts;

    public int BlogId { get; set; }
    public string Url { get; set; }

    public virtual ICollection<Post> Posts
    {
        get
        {
            if (_posts == null)
            { _posts = new Collection<Post>(); }
            return _posts;
        }
        protected set
        { _posts = value; }

    }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }

    public Blog Blog { get; set; }
}
然后我写下面的代码:

using (var db = new BloggingContext())
{
    var blog = new Blog() { Url = DateTime.Now.ToString() };
    blog.Posts.Add(new Post() { Title = "Foo", Content = "Foo" });
    blog.Posts.Add(new Post() { Title = "Bar", Content = "Bar" });

    db.Blogs.Add(blog);
    var count = db.SaveChanges();

    Console.WriteLine("{0} records saved to database", count);

    return blog.BlogId;
}

调用SaveChanges后,blog对象有一个BlogId,但两个BlogId对象中的Post仍为-1,并且没有任何内容添加到数据库。

1 个答案:

答案 0 :(得分:1)

自EF 7测试版6开始,调用DbSet<T>.Add(obj)仅添加obj,而不是与obj相关联的所有实体。

在您的情况下,您还需要为每个新帖子致电db.Posts.Add(post)

此行为可能会在EF 7 RTM之前发生变化。您可以通过在GitHub上观看此问题来关注此API的更改:Decide on Add() behavior with graphs #2726