Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

Many-To-Many join table handling #5178


User avatar
0
mikatmlvertti created

Hi

Is there predefined practice for many-to-many join tables. I have object1 and object2 with many to many connection and for that connection I have join table with both objects id:s. IRepository needs entity with primary key, but I was wondering if there is allready some other way without the need of id for jointable.


3 Answer(s)
  • User Avatar
    0
    alper created
    Support Team

    An example to many-to-many relation. Entities: Student, Course.

    ublic class Student
    {
        public Student() 
        {
            this.Courses = new HashSet<Course>();
        }
    
        public int StudentId { get; set; }
        [Required]
        public string StudentName { get; set; }
    
        public virtual ICollection<Course> Courses { get; set; }
    }
            
    public class Course
    {
        public Course()
        {
            this.Students = new HashSet<Student>();
        }
    
        public int CourseId { get; set; }
        public string CourseName { get; set; }
    
        public virtual ICollection<Student> Students { get; set; }
    }
    
    public class SchoolDBContext : DBContext
    {
       
        public DbSet<Student> Students { get; set; }
        public DbSet<Course> Courses { get; set; }
            
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }
    

    [attachment=1:2qaypakn]manytomany-fg[1].PNG[/attachment:2qaypakn]


    <ins><span style="color:#FF0000">Configure a Many-to-Many Relationship using Fluent API:</span></ins>

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    
        modelBuilder.Entity<Student>()
                    .HasMany<Course>(s => s.Courses)
                    .WithMany(c => c.Students)
                    .Map(cs =>
                            {
                                cs.MapLeftKey("StudentRefId");
                                cs.MapRightKey("CourseRefId");
                                cs.ToTable("StudentCourse");
                            });
    
    }
    

    [attachment=1:2qaypakn]manytomany-fg[1].PNG[/attachment:2qaypakn]

  • User Avatar
    0
    mikatmlvertti created

    Hi alper. I got that far, but now I am about to create appservice and I was wondering how to create query for jointable, since IRepository<StudentCources> is not possible.

  • User Avatar
    0
    ismcagdas created
    Support Team

    If you are using EF Core, it is not yet supported <a class="postlink" href="https://docs.microsoft.com/en-us/ef/core/modeling/relationships#many-to-many">https://docs.microsoft.com/en-us/ef/cor ... ny-to-many</a>.