EF7 not saving object graph

entity-framework-core

Question

I expect I'll feel like an idiot when I figure out the answer to this, but I just cannot figure out why EF7 isn't saving the object graph the same way I'm used to it working in EF6.

My context is:

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; }
}

I then write the following code:

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;
}

After SaveChanges is called the blog object has a BlogId but the BlogId in the two Post objects is still -1 and nothing gets added to the database.

Accepted Answer

As of EF 7 beta 6, calling DbSet<T>.Add(obj) only adds obj, not all of the entities associated with obj.

In your case, you also need to call db.Posts.Add(post) for each new post.

This behavior will likely change before EF 7 RTM's. You can follow changes to this API by watching this issue on GitHub: Decide on Add() behavior with graphs #2726



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why