I have EF 4 implemented in the project. Within it, there are tables customer and order. Which has relationship one (customer) to many (order).
I’m creating a viewmodel for both (CustomerViewModel and OrderViewModel) to be passed from my domain layer to interface layer (MVC in this case).
Now the question is “do I need to reference both viewmodel? for example in customerviewmodel has IEnumerable<OrderViewModel> and in orderviewmodel has CustomerViewModel. If so how do I design it (as a best practice) so that IEnumerable<OrderViewModel> and CustomerViewModel is populated with the correct reference?
I would always drive the design of ViewModels with the specific view in mind, never from the viewpoint of the domain model (= the entities). How a ViewModel looks depends on what you want to display and what you want to modify in a view.
As a result you don’t have THE
OrderViewModeland THECustomerViewModelbecause you have different views which will display or edit an order or customer or parts of these. So, you have those ViewModels for a specific purpose and view and therefore multiple times in different variations.Suppose, you have an
OrderEditViewand this view will allow to edit order information and display the customer of that order. You would have anOrderEditViewModellike this:This
OrderEditCustomerViewModeldoesn’t need a reference to theOrderEditViewModel.You can populate this ViewModel like so:
On the other hand, if you have a
CustomerEditViewwhich allows editing customer information and displays the orders of the customer in a list, the ViewModel might be:Here
CustomerEditOrderViewModeldoesn’t need a reference to theCustomerEditViewModeland you can create the ViewModel from the database this way for example:The
Customer(*)ViewModels and theOrder(*)ViewModels are different – regarding the necessary references, the properties and the data annotations, depending on the view where they are used.With these considerations in mind the question for mutual correct references between the
OrderViewModeland theCustomerViewModeldisappears because you normally don’t need such a bidirectional reference for your views.