My models are:
public class Presentation
{
public int PresentationId { get; set; }
public string PresentationTitle { get; set; }
public DateTime PresentationTime { get; set; }
public Level? Level { get; set; }
public virtual Professor Professor { get; set; }
}
public class Professor
{
public int ProfessorId { get; set; }
public string Name { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Presentation> Presentations { get; set; }
}
Level
is an enum
, forget about it for now. I have a web page where I try to add a new Presentation
. This means I am adding a title
,time
,level
and a professor
. The professor
is added through a DropDownList
.
if (!IsPostBack)
{
drpProfessor.DataSource = db.Professors.ToList();
drpProfessor.DataTextField = "Name";
drpProfessor.DataValueField = "ProfessorId";
drpProfessor.DataBind();
}
The DropDownList
is populated with the names, but on Save action I get a NullReference
Exception. Save looks like this:
Presentation newPres = new Presentation();
newPres.PresentationTitle = txtPresentationTitle.Text;
newPres.Level = ParseEnum<Level>(drpLevel.SelectedValue);
newPres.PresentationTime = calendar.SelectedDate;
newPres.Professor.ProfessorId = Convert.ToInt32(drpProfessor.SelectedItem.Value);
db.Presentations.Add(newPres);
db.Entry(newPres).State = System.Data.EntityState.Added;
db.SaveChanges();
litMsg.Text = "New presentation added!";
Please ignore again the Level
,it's working fine. But the error is at:
newPres.Professor.ProfessorId = Convert.ToInt32(drpProfessor.SelectedItem.Value);
I am trying to add the value (ProfessorId
) of the selected item to db, but I get:
Object reference not set to an instance of an object.
I checked and the value(ProfessorId
) is selected from the DropDownList
.