I'm trying to develop an application for school and I'm stuck. I want to add skills to a person using a Many-to-many relation in the database, so of course there's a table in between. I'm getting this error; Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set
to an instance of an object.
Source Error:
Line 99: var Skill = new Skill { ID = Skill_ID };
Line 100: var Teacher = new Teacher { ID = Teacher_ID };
**Line 101: Skill.Teachers.Add(Teacher);**
Line 102: db.SaveChanges();
Line 103: }
This is my controller;
// GET: MyProfile/AddkSkills/
public ActionResult AddSkills()
{
var skills = (from s in db.Skills
select s); /*new Skill { ID = s.ID, SkillName = s.SkillName });*/
var Model = new AddSkillsViewModel
{
Skills = skills.ToList(),
};
return View(Model);
}
//POST: MyProfile/AddkSkills/
[HttpPost]
public ActionResult AddSkillsPost()
{
int Teacher_ID = Convert.ToInt32(Session["Teacher_ID"]);
var SkillsArray = Request.Form["chk_group[]"];
if (SkillsArray != null)
{
foreach (var skill in SkillsArray)
{
int Skill_ID = Convert.ToInt32(skill);
var Skill = new Skill { ID = Skill_ID };
var Teacher = new Teacher { ID = Teacher_ID };
Skill.Teachers.Add(Teacher);
db.SaveChanges();
}
}
return RedirectToAction("MyProfile");
}
Add Skill form;
<h2>AddSkills</h2>
<form name="addSkillsForm" action="AddSkillsPost" method="post">
@foreach (var skill in Model.Skills)
{
<input type="checkbox" name="chk_group[]" value="@skill.ID" />@skill.SkillName< br />
}
<input type="submit" value="Update Skills" />
</form>
Edit1;
Skill Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Ability_Examen_ASP.Models
{
[Table("Skills")]
public class Skill
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public string SkillName { get; set; }
public virtual List<Teacher> Teachers { get; set; }
}
}