I am trying to learn mvc – I apologize in advance for all the silly questions. What I’ve done is created an mvc proejct based on an exsiting database, and then i’ve been disecting it to try to understand what’s been created for me, and how to create my own stuff. Unfortunately, because I’m a new stackoverflow user, i can’t post a picture of my project structure.
i have a parent controller and a child controller created using the wizard based on 2 separate tables i have in my model. I want to display both of them in one view – ultimately in a webgrid and be able to change data for any parent item, or child item. You can ignore the CombinedController for now. I’ve been doing some reading and i’ve learned that i should be creating a viewmodel that combines both the parent and child at the model level, and then go from there.
so i created this class:
Imports System.Data.Objects.DataClasses
Public Class ParentAndChild
Public Property myChildren As IEnumerable(Of Child)
Public Property myParent as Parent
End Class
I have a few questions:
Question 1
Do i have to add this ParentAndChild entity into the .edmx file in order to create a controller and view for it? I guess what I’m really asking is do i have to create a view in the sql database first, have the entity show up in the .edmx and then create a controller? Or can I just combine the two entities in a class? That’s what i’ve done so far. I don’t have a sql View in my database combining these two tables. The reason why I ask is because when i create my controller, if i want to get all the CRUD for free, i have to create using the Entity Framework. But I don’t know what to specify for the data context.
Question 2
If i want a webgrid to somehow show all my parents and all their children, will the new ParentAndChild class work? I think that will only show the details for One parent and its children. I think i need to create a list of parents.. and then in the parentlist for each parent, add a collection of modules. But i don’t know how to do this..
Question 3
How does the entityframework know which modules to return when i’m using my new class? I don’t define the relationship anywhere… Is it because in the .edmx file, the system knows the relationships between the tables?
If you simply need to access the information of a parent entity and its child entity’s you should be able to send your view the parent entity. A ViewModel is not absolutely necessary for this if Entity Framework knows about the relationship between the two entity’s. If the relationship between the 2 tables exists at the database level then Entity Framework should have modeled it automatically.
An example of a controller would be:
If you need to create a table of all the child entity’s you could do something like this: