asp.net-core - EF Core 中的一对多关系
问题描述
我在学习 .net core mvc 时尝试学习 Entity Framework 我想不明白创建一对多表关系的最佳实践是什么:
这是2个模型:
public class BookCategory
{
[Key]
public int IdCategory { get; set; }
[Required]
public string Description { get; set; }
}
public class Book
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Author { get; set; }
public string ISBN { get; set; }
public int IdCategory { get; set; }
public BookCategory BookCategory { get; set; }
}
// dBContext
public DbSet<Book> Books { get; set; }
public DbSet<BookCategory> BookCategories { get; set; }
我不确定这是否是在 mvc 中创建关系的最佳方法,因为在 update-database 调用之后,我在“book”表中看到了“BookCategoryIdCategory”字段,我认为这不正确。
你能帮我吗 ?
更新:我忘了更好地解释:
在更新数据库之后的数据库中,我希望看到:
(table book)
int Id (primary key)
string Name
string Author
string ISBN
int IdCategory (relation with IdCategory of BookCategory
(table bookcategory)
int IdCategory (primary key relation with IdCategory of book)
string Description
如果可能,没有其他字段。
解决方案
如果一个 BookCategory 可以有很多书,那么可以说它有一个图书列表。
在您的 Book Category 类中,添加:
public List<Book> Books { get; set; }
推荐阅读
- python - 如何有效地删除海龟列表
- python - 请在描述中解释真正发生的事情
- kubernetes - Kubernetes 裸机集群 - 重置问题。部分节点未排空
- javascript - js函数的顺序
- dart - 如何在 Dart 中实现 memoization?
- button - 使用带有 onclick 事件的 Dom 更改背景颜色
- rust - 如何使用泛型参数包装函数,这些参数强制命名生命周期在 rust 中具有非“静态生命周期”
- jsp - 如何使用 aem 中的注释创建自定义标签库
- microprocessors - 8085微处理器中的程序
- cron - crontab expression to schedule a DAG in Apache Airflow