Aida-Hagh / EF-Core

Learn EF Core
1 stars 0 forks source link

Fluent API رابطه چند به چند با #11

Open Aida-Hagh opened 4 months ago

Aida-Hagh commented 4 months ago

برای مثال، یک Student می‌تواند در چندین Course شرکت کند و یک Course می‌تواند چندین Student داشته باشد.

public class Student {

public int StudentId { get; set; }
public string Name { get; set; }
public ICollection<StudentCourse> StudentCourses { get; set; }

}

public class Course {

public int CourseId { get; set; }
public string Title { get; set; }
public ICollection<StudentCourse> StudentCourses { get; set; }

}

public class StudentCourse //کلاس واسط {

public int StudentId { get; set; }
public Student Student { get; set; }

public int CourseId { get; set; }
public Course Course { get; set; }

}


using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext {

public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<StudentCourse> StudentCourses { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFCoreManyToMany;Trusted_Connection=True;");
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<StudentCourse>()
        .HasKey(sc => new { sc.StudentId, sc.CourseId });

    modelBuilder.Entity<StudentCourse>()
        .HasOne(sc => sc.Student)
        .WithMany(s => s.StudentCourses)
        .HasForeignKey(sc => sc.StudentId);

    modelBuilder.Entity<StudentCourse>()
        .HasOne(sc => sc.Course)
        .WithMany(c => c.StudentCourses)
        .HasForeignKey(sc => sc.CourseId);
}

}


using System; using System.Linq;

class Program {

static void Main(string[] args)
{
    using (var db = new AppDbContext())
    {
        // ایجاد پایگاه‌داده
        db.Database.EnsureCreated();

        // افزودن داده‌ها
        var student = new Student { Name = "John Doe" };
        var course = new Course { Title = "C# Programming" };
        db.Students.Add(student);
        db.Courses.Add(course);
        db.SaveChanges();

        // ایجاد رابطه چند به چند
        var studentCourse = new StudentCourse { StudentId = student.StudentId, CourseId = course.CourseId };
        db.StudentCourses.Add(studentCourse);
        db.SaveChanges();

        // خواندن و نمایش داده‌ها
        var students = db.Students
                         .Include(s => s.StudentCourses)
                         .ThenInclude(sc => sc.Course)
                         .ToList();

        foreach (var s in students)
        {
            Console.WriteLine($"{s.Name} is enrolled in:");

            foreach (var sc in s.StudentCourses)
            {
                Console.WriteLine($" - {sc.Course.Title}");
            }
        }
    }
}

}