EF Core 2.2 导航 属性 创建重复条目

EF Core 2.2 navigational property creating a duplicate entry

对于 现有博客 实体,我正在添加一个 新 Post 和 Blog 作为导航 属性。错误是插入了 重复的博客 。使用 EF 核心 2.2

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>()
            .HasOne(p => p.Blog)
            .WithMany(b => b.Posts)
            .HasForeignKey(p => p.BlogId);
    }
}

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

    public List<Post> Posts { get; set; }
}

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

PostFactory.cs

  public Post CreateNew(Guid id)
    {
        var post = new Post(id);

        return post;
    }

PostService.cs

   public Post Create(Guid blogId)
    {
        var blog = _context.Blogs.Include(t=>t.Posts).FirstOrDefault(x => x.Id == blogId);

        var postFactory = new PostFactory();
        var post = postFactory.CreateNew(Guid.NewGuid());

        post.Blog = blog;
        post.BlogId = blogId;

        blog.Posts.Add(post);
        _context.SaveChanges();
        return post;
    }

不确定为什么现有博客再次尝试插入到数据库中。我得到一个错误:

违反 PRIMARY KEY 约束 'PK_Blogs'。无法在对象 'dbo.Blogs'

中插入重复键

您应该在 post 中分配 blogId 或将 post 添加到博客,我相信两者都会给您带来意想不到的结果,试试这个:

public Post Create(Guid blogId)
{
    var blog = _context.Blogs.Include(t=>t.Posts).FirstOrDefault(x => x.Id == blogId);

    var postFactory = new PostFactory();
    var post = postFactory.CreateNew(Guid.NewGuid());

    blog.Posts.Add(post);
    _context.SaveChanges();
    return post;
}