我正在尝试为学校开发应用程序而且我被困住了。我想在数据库中使用多对多关系为一个人添加技能,所以当然中间有一个表。我收到了这个错误; ' /'中的服务器错误应用
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: }
这是我的控制者;
// 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");
}
添加技能表单;
<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;
技能模型
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; }
}
}
答案 0 :(得分:1)
当您创建新的Skill
对象时,我假设它的Teachers
属性为null。您可能需要将该属性初始化为空列表(或其他)。
一种常见的技术是让Skill
类的默认构造函数(等)自动为每个这样的属性创建新的集合。
例如(假设您的Skill
和Teacher
类的定义方式):
public class Skill
{
public Skill()
{
this.Teachers = new List<Teacher>();
}
}
(只需将内部部分添加到现有类中)。
如果您使用的是EF Database-First,这是自动完成的,因此我假设您使用的是Code-First。
答案 1 :(得分:0)
在这种情况下,我认为你最好只创建一个类似
的联结表[Table("TeacherSkills")]
public class TeacherSkill
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public int TeacherID { get; set; }
[ForeignKey("TeacherID ")]
public Teacher Teacher { get; set; }
[Required]
public int SkillID{ get; set; }
[ForeignKey("SkillID")]
public Skill Skill { get; set; }
}
然后你只需要将你的外键添加到教师和技能中,然后插入一项新技能
db.TeacherSkill.Add(new TeacherSkill(){TeacherID = Teacher_ID, SkillID = Skill_ID});
db.SaveChanges();