首页 > 解决方案 > 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

如果可能,没有其他字段。

标签: asp.net-coreentity-framework-core

解决方案


如果一个 BookCategory 可以有很多书,那么可以说它有一个图书列表。

在您的 Book Category 类中,添加:

public List<Book> Books { get; set; }

推荐阅读