if not using any kind of IRepository pattern:
Create
Adding new student with subjects
using(var dbContext = new Model1Entitites()){
var student = new Student{details..};
student.Add(new Subject{});
dbContext.Students.Add(student);
dbContext.SaveChanges();
}
Update
Adding subjects to an existing student
using(var dbContext = new Model1Entities()){
objectToAddTo = dbContext.studentMaster.SingleOrDefault(x=> x.id == id);
objectToAddTo.Subjects.Add(new Subject{});
dbContext.SaveChanges();
}
Adding existing subjects to an existing student
var student = db.Students.FirstOrDefault(x=> x.Id == id);
var subjectToAdd = db.Subjects.FirstOrDefault(x=> x.id == SubjectId);
if(student!= null){
if(subjectToAdd != null){
student.Subjects.Add(subjectToAdd);
}
}
db.SaveChanges();
Remove subject from student
using(var dbContext = new Model1Entities()){
objectToRemoveFrom = dbContext.studentMaster.SingleOrDefault(x=> x.id == id);
var subjectToRemove = dbContext.Subjects.SingleOrDefault(x=> x.subjectid==subjectid);
objectToRemoveFrom.Subjects.Remove(subject);
dbContext.SaveChanges();
}
Select
using(var dbContext = new Model1Entities()){
return dbContext.Students.Include(x=> x.Subjects);
}
For adding multiple connections the other way around, do the same with the other object.
Returning something to view when dealing with connections
Since razor is not always happy with getting entities containing connection entitites, you should probably create a new model for the view instead of using the entity proxy.
Controller
var model = new StudentModel();
var student = db.Students.Include(x=> x.Subjects);
//here you can use example AutoMapper, or you can do it manually
model.Id = student.id;
model.Name = student.Name;
model.Subjects = db.Students.Subjects.Select(x=> new SubjectModel{Id = x.Id, Name = x.Name}).ToList();
return View(model);
ViewModel
public class StudentModel{
public int Id{get;set;}
public string Name{get;set;}
public List<SubjectModel> Subjects{get;set;}
}
public class SubjectModel{
public int Id{get;set;}
public string Name{get;set;}
}
Razor
@model StudentModel;
<span>Student name @Model.Name</span>
<ul>
@foreach(var subject in Model.Subjects){
<li id="@subject.Id">@subject.Name</li>
}
<ul>