作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一些文章和一些作者,想将它们链接为:
我使用本教程创建了多对多关系: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/
我是一名优秀的程序员,十分优秀!