dev.e.loper
dev.e.loper

Reputation: 36044

Linq InsertOnSubmit is throwing exception: Object reference not set to an instance of an object

The following throws exception.

The course object that is being passed to InsertOnSubmit is of type Course that is generated by Linq.

 public ActionResult Course(CourseViewModel c)
 {
    Course course = (Course) c; //CourseViewModel is derrived from Course
    SchedulerDataContext db = new SchedulerDataContext();
    db.Courses.InsertOnSubmit(course);  // <- this is where exception is thrown
    db.SubmitChanges();
 }

There are already questions about this here and here, however, I don't understand their answer. Supposedly I'm not creating an object in time. Which object and what exactly needs to happen?

Upvotes: 0

Views: 2378

Answers (1)

tvanfosson
tvanfosson

Reputation: 532545

You need to create the Course object before you try to insert it.

Course course = new Course { ... set the properties .. };
SchedulerDataContext db = new SchedulerDataContext();
db.Courses.InsertOnSubmit(course);
db.SubmitChanges();

Upvotes: 1

Related Questions