EntityFramework Same Table Many to Many Relationship

前端 未结 2 1815
梦谈多话
梦谈多话 2020-12-02 22:22

I have a table called Products which obviously contains products. However, I need to create related products. So what I\'ve done is create a junction table called product_re

2条回答
  •  一个人的身影
    2020-12-02 22:45

    Lets take your Example:

    Related table

      Related_id      PK
      Related_name
      Date
    

    Product Table

      Product_id      PK
      Related_id      FK
      Product_Name
      Date
    

    How to Represent it in EF

    Related Model Class named as RelatedModel

      [Key]
      public int Related_id { get; set; }
    
      public string Related_name {get;set}
    
      public Datetime Date{get;set;}
    

    Product Model Class named as ProductModel

       [Key]
      public int Product_id { get; set; }
    
      public string Product_name {get;set}
    
      public string Related_id {get;set}
    
      public Datetime Date{get;set;}
    
      [ForeignKey("Related_id ")]      //We  can also specify here Foreign key
      public virtual RelatedModel Related { get; set; } 
    

    In this way we can Create Relations between Two table

    Now In Case of Many to Many Relation I would like to take another Example here

    Suppose I have a Model Class Enrollment.cs

    public class Enrollment
    {
        public int EnrollmentID { get; set; }
        public int CourseID { get; set; }
        public int StudentID { get; set; }
        public decimal? Grade { get; set; }
        public virtual Course Course { get; set; }
        public virtual Student Student { get; set; }
    }
    

    Here CourseID and StudentId are the two foreign Keys

    Now I Have another Class Course.cs where we will create Many to Many Relation.

    public class Course
    {
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }
        public virtual ICollection Enrollments { get; set; }
    }
    

    Hope This will help!!!

提交回复
热议问题