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

前端 未结 2 1484
粉色の甜心
粉色の甜心 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<Book> Books { get; set; }
    }
    [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
    public class StudentModelContext : DbContext
    {
        public DbSet<Book> Books { get; set; }
        public DbSet<Author> 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;
    
    0 讨论(0)
  • 2021-01-26 00:52

    Try to add 2 Students in your Review class, for example:

    [Table("tb_review")]
    public class Review
    {    
        [Key]
        public int id { get; set; }
        public string message { get; set; }
        public Student student{ get; set; } // review of which student
        public Student reviewer{ get; set; } // whom send the review
    } 
    

    And your Student class should be like this:

    [Table("tb_student")]
    public class Student
    {    
        [Key]
        public int id { get; set; }
        public string name { get; set; }
        [InverseProperty("student")]
        public List<Review> reviewAbout{ get; set; }
        [InverseProperty("reviewer")]
        public List<Review> reviewBy{ get; set; }
    } 
    
    0 讨论(0)
提交回复
热议问题