How to have multiple one-to-many relations between two entities using Entity Framework Code First

前端 未结 2 1512
粉色の甜心
粉色の甜心 2021-01-26 00:05

Below is a simple approach to save relational database records which is working perfectly fine. I have doubt on one scenario. Before that i need to know the way i am approaching

2条回答
  •  没有蜡笔的小新
    2021-01-26 00:47

    namespace MvcApplication4.Models
    {
     [Table("tb_book")]
    public class Book
    {
        [Key]
        public int ID { get; set; }
        public string Title { get; set; }
    
        [InverseProperty("Books")]
        public Author Author { get; set; }
    }
    [Table("tb_author")]
    public class Author
    {
        [Key]
        public int ID { get; set; }
        public string Name { get; set; }
    
        [InverseProperty("Author")]
        public ICollection Books { get; set; }
    }
    [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
    public class StudentModelContext : DbContext
    {
        public DbSet Books { get; set; }
        public DbSet Authors { get; set; }
    }
    }
    

    Table structure


    CREATE TABLE `tb_book` (
    `ID` int(11) NOT NULL AUTO_INCREMENT,
    `Title` varchar(45) DEFAULT NULL,
    `Author_ID` int(11) DEFAULT NULL,
    PRIMARY KEY (`ID`),
    KEY `ab_idx` (`Author_ID`),
    CONSTRAINT `ab` FOREIGN KEY (`Author_ID`) REFERENCES `tb_author` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
    
    
    CREATE TABLE `tb_author` (
    `ID` int(11) NOT NULL AUTO_INCREMENT,
    `Name` varchar(45) DEFAULT NULL,
     PRIMARY KEY (`ID`)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
    

提交回复
热议问题