gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:38:16 26 4
gpt4 key购买 nike

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

  • 任何文章都可以有任意数量的作者和
  • 每个作者都可以写任意数量的文章

我使用本教程创建了多对多关系: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; }
}

文章作者

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

public Article Article { get; set; }

public int AuthorId { get; set; }

public Author Author { get; set; }
}

数据库上下文

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 database update 后,表按预期创建了

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

服务

// 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: The property 'AuthorId' on entity type 'ArticleAuthor' has a temporary value. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.

最佳答案

试试这个payload,ArticleId和AuthorId应该是必须的,ArticleId在父类中是隐含的,所以你至少应该提供AuthorId:

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

关于c# - 如何在 Entity Framework Core 中配置多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54348328/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com