New to MVC so I’m sure there is a proper way to do this that I’m missing.
I have a Entity “Event” that has a child/related Entity “EventTime”. When I created my Edit Action I could load the Event model fine with a linq statement.
Event mEvent = db.Events.Single(s => s.EventID == id);
Then in my view I access the child by walking the object:
@Html.EditorFor(model => model.Event.EventTime.DateStart)
This works great. Edit Action gets the values, does the magic binding and saves changes.
UpdateModel(mEvent);
db.SaveChanges();
Now to my Problem. The Create Action. In the sample Music Store app on asp.net they tell you to create a new empty model to pass to your view.
Event mEvent = new Event();
However my view gets an exception when it hits any reference to the child entity Event.EventTime. Also in the controller create action if I try to set any properties after creating the new mEvent object I get an Object reference exception.
Event.EventTime.DateStart = DateTime.Now;
I thought EF would magically create the child when you access it. I assume the issue is because I’m not creating the model from the db, it has no foreign key values to reference the objects together?
So how am I suppose to do this? I thought about a ViewModel and loading up each entity in that, then on my HTTPPost Action I assume I’d have to update the DB in lowest child first order and update the references as each one is saved to the database? Seems like it would work but feels like it’s defeating the purpose of EF.
Thanks for you help.
Morten, you are right. I had to create an instance of the EventTime object and assign it to Event.EventTime. That worked. I guess it makes sense it wouldn’t do it for me automatically. Thx for the comments.