0

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?

Community
  • 1
  • 1
dev.e.loper
  • 35,446
  • 76
  • 161
  • 247

1 Answers1

1

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();
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • Weird because I was doing Course course = (Course)CourseModelView where CourseModelView inherits Course object. So course object was set. – dev.e.loper Oct 05 '11 at 02:46
  • @dev.e.loper Inheritance can be tricky unless you have your data context set up properly for it. Can you try creating just a new Course and copying the properties from the model to it instead of doing the cast? That may not be your problem, but I'd need to see more code if that isn't it. – tvanfosson Oct 05 '11 at 02:51
  • Course object was already set but not the way you described. I updated my question with lines that describe how I set it. Can you tell me why the way I had it didn't work? – dev.e.loper Oct 05 '11 at 02:53
  • doing it the way you describes works. However now I need to copy all the properties manually which kinda sucks. I was hoping to create a ModelView object that inherits Course object, then I can add to ModelView object whatever else the View needs but then also use it when persisting it to database. – dev.e.loper Oct 05 '11 at 02:55
  • Are you sure that the model was bound properly, i.e., `c` is non-null? If that's not it, then I suspect it's a framework thing because of inheritance. LINQ to SQL supports inheritance but needs a discriminator column to make it work. You're not using it that way, but it could be confusing the framework because it expects that you will have set up the inheritance in your model. Casting the object to the parent type doesn't change it's type, it just limits the interface to the parent interface. It's still the child type under the hood. I'm only guessing here, I have used inheritance in LINQ. – tvanfosson Oct 05 '11 at 02:58
  • 1
    @dev.e.loper you might want to look into AutoMapper. It will let you set up your entity to view model mappings in a single place, then simply call the mapping method to create one from the other. – tvanfosson Oct 05 '11 at 03:00