EF7不保存對像圖


當我找到答案時,我希望我會覺得自己像個白痴,但我無法弄清楚為什麼EF7沒有像我習慣在EF6中工作一樣保存對像圖。

我的背景是:

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

然後我寫下面的代碼:

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

在調用SaveChanges之後, blog對象具有BlogId但兩個PostBlogId中的BlogId仍為-1,並且沒有任何內容添加到數據庫中。

一般承認的答案

從EF 7 beta 6開始,調用DbSet<T>.Add(obj)只會添加obj ,而不是所有與obj相關的實體。

在您的情況下,您還需要為每個新帖子調用db.Posts.Add(post)

在EF 7 RTM之前,此行為可能會發生變化。您可以通過在GitHub上觀察此問題來跟踪對此API的更改: 使用圖形#2726確定Add()行為





許可下: CC-BY-SA
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因