Reputation: 13616
I am working on my tutorial project I am new to entity framework.
I have many two many relationship tables I am using code first approach:
Here is tables definition:
class EmployeeDBContext : DbContext
{
public EmployeeDBContext() : base("DefaultConnection") { }
public DbSet<Course> Courses { get; set; }
public DbSet<Student> Students { get; set; }
}
//================================================My entities=================================================
public class Student
{
[Key]
public int StudentID { get; set; }
public string StudentName { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class Course
{
[Key]
public int CourseID { get; set; }
public string CourseName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
The course table filled with 3 subjects: History, Math, Physics.
I need to add new student and to relate the student to existing courses.
Any idea how can I implement it?
Upvotes: 4
Views: 141
Reputation: 134
Try code below: Depends if you want to update the courseName or add student list.
public void UpdateCourse(string courseName, List<Student> students)
{
var dbInstance = new EmployeeDBContext();
Course model = (from item in dbInstance.Courses
where item.CourseID = courseid
select item);
model.CourseName = courseName;
foreach(var item in students)
{
var currentStudent = from stud in dbInstance.Students
where stud.StudentId == item.StudentId;
if( currentStudent != null)
currentStudent.Name = item.Name;
else
dbInstance.Students.Add(new Student() {.StudentId = item.StudentId, .Name = item.Name});
};
dbInstance.SaveChanges();
}
public void CreateCourse(string courseName, List<Student> students)
{
var model = new Course();
model.CourseName = courseName;
model.Students = students;
var dbInstance = new EmployeeDBContext();
dbInstance.Courses.Add(model);
dbInstance.SaveChanges();
}
Upvotes: 2
Reputation: 6491
If you need to create a student and add a course (or more courses) to him the way to do it with EF is the same as described with words...
using (var ctx= new EmployeeDBContext())
{
// Create a new student (and set some properties)
Student student = new Student()
{
StudentName = "Scott Tiger"
};
// Replace courseId with the course id that you need to add to the student
student.Courses.Add(ctx.Courses.Find(courseId));
// Add other courses if you need to
// Let's write the student to the DB
ctx.Students.Add(student);
ctx.SaveChanges();
}
Upvotes: 2