如何在Entity Framework Core中配置多对多关系

时间:2019-01-24 13:57:30

标签: c# entity-framework .net-core

我有一些文章和一些作者,并希望将它们链接为:

  • 任何文章可以有任意数量的作者和
  • 每个作者都可以撰写他们想要的任何文章

我使用以下教程创建了ManyToMany关系:https://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration

这是我定义班级的方式。

文章

public class Article
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public string Title { get; set; }

    public DateTime Date { get; set; }

    public ICollection<ArticleAuthor> ArticleAuthors { get; set; }
}

作者

public class Author
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Column(TypeName = "text")] public string Name { get; set; }

    [Column(TypeName = "text")] public string Email { get; set; }

    public ICollection<ArticleAuthor> ArticleAuthors { get; set; }
}

ArticleAuthor

public class ArticleAuthor
{
    public int ArticleId { get; set; }

    public Article Article { get; set; }

    public int AuthorId { get; set; }

    public Author Author { get; set; }
}

DbContext

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    public DbSet<Article> Articles { get; set; }

    public DbSet<Author> Authors { get; set; }

    public DbSet<ArticleAuthor> ArticleAuthors { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ArticleAuthor>()
            .HasKey(bc => new {bc.ArticleId, bc.AuthorId});
        modelBuilder.Entity<ArticleAuthor>()
            .HasOne(bc => bc.Article)
            .WithMany(b => b.ArticleAuthors)
            .HasForeignKey(bc => bc.ArticleId);
        modelBuilder.Entity<ArticleAuthor>()
            .HasOne(bc => bc.Author)
            .WithMany(c => c.ArticleAuthors)
            .HasForeignKey(bc => bc.AuthorId);
    }
}

在我运行 dotnet ef数据库更新

后,将按预期创建表

一切似乎都很好,除了当我尝试通过此服务与作者添加文章时:

服务

// POST: api/Articles
[HttpPost]
public async Task<IActionResult> PostArticle([FromBody] Article article)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    _context.Articles.Add(article);
    await _context.SaveChangesAsync();

    return Ok(article);
}

JSON

{
    "Title":"Title 2",
    "ReadingTime" : 2,
    "Date":"01.12.2019",
    "Theme": "1",
    "ArticleAuthors":[
        {
            "ID":"1"
        }
    ]
}

当我尝试与作者添加文章时,我一直陷在这个错误中

  

System.InvalidOperationException:实体类型“ ArticleAuthor”上的属性“ AuthorId”具有一个临时值。要么显式设置一个永久值,要么确保将数据库配置为为此属性生成值。

1 个答案:

答案 0 :(得分:1)

尝试此有效负载,应要求有ArticleId和AuthorId,ArticleId在父类中是隐式的,因此您至少应提供AuthorId:

{
    "Title":"Title 2",
    "ReadingTime" : 2,
    "Date":"01.12.2019",
    "Theme": "1",
    "ArticleAuthors":[
        {
            "AuthorId":"1"
        }
    ]
}