Dinesh Kudale

Dinesh Kudale

  • NA
  • 127
  • 17.9k

How to implement many to many relationship in Asp.Net Mvc ..

Jul 15 2018 2:09 AM
In Index() method of School controller, Which code need to write by me? Please, explain. I don't want to use fluent API. I want to implement it using Data Annotation.

 
 In Model Folder, I have created Student.cs class
  1. public class Student  
  2.     {  
  3.         public int StudentId { getset; }  
  4.         public string StudentName { getset; }  
  5.         public ICollection<Course> CoursesNProperty { getset; }  
  6.     }  
In Model Folder, I have created Course.cs class
  1. public class Course  
  2.     {  
  3.         public int CourseId { getset; }  
  4.         public string CourseName { getset; }  
  5.         public ICollection<Student> StudentsNProperty { getset; }  
  6.     }  
In Model Folder, I have created SchoolContext.cs class
  1. public class SchoolContext :DbContext  
  2.     {  
  3.         public SchoolContext() : base("name=conStr") { }  
  4.         public DbSet<Student> Students { getset; }  
  5.         public DbSet<Course> Courses { getset; }  
  6.     }  
In web.config file
  1. <connectionStrings>    
  2.     <add name="conStr" connectionString="Data Source=Dinesh\Aaradhya;Database=GopinathSchoolMToM;User Id=sa;Password=test123" providerName="System.Data.SqlClient"/>  
  3.   </connectionStrings>  
In controller Folder, I have created School controller
  1. using Note7Page124CascadeMToM.Models;  
  2. namespace Note7Page124CascadeMToM.Controllers  
  3. {  
  4.     public class SchoolController : Controller  
  5.     {  
  6.         SchoolContext db = new SchoolContext();  
  7.         // GET: School  
  8.         public ActionResult Index()  
  9.         {  
  10.             Student student1 = new Student()  
  11.             {  
  12.                 StudentName = "Prakash"  
  13.             };  
  14.             Student student2 = new Student()  
  15.             {  
  16.                 StudentName = "Shubham"  
  17.             };  
  18.             Course course1 = new Course()  
  19.             {  
  20.                 CourseName = "Asp.Net"  
  21.             };  
  22.             Course course2 = new Course()  
  23.             {  
  24.                 CourseName="C#.Net"  
  25.             };  
  26.             //Which code need to implement here? ...  
  27.             return View();  
  28.         }  
  29.     }  
  30. }  
 

Answers (1)