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 OrderViewModel
and THE CustomerViewModel
because 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 OrderEditView
and this view will allow to edit order information and display the customer of that order. You would have an OrderEditViewModel
like this:
public class OrderEditViewModel
{
public int OrderId { get; set; }
public DateTime? ShippingDate { get; set; }
[StringLength(500)]
public string Remark { get; set; }
//...
public OrderEditCustomerViewModel Customer { get; set; }
}
public class OrderEditCustomerViewModel
{
[ReadOnly(true)]
public string Name { get; set; }
[ReadOnly(true)]
public string City { get; set; }
// ...
}
This OrderEditCustomerViewModel
doesn't need a reference to the OrderEditViewModel
.
You can populate this ViewModel like so:
var orderEditViewModel = context.Orders
.Where(o => o.OrderId == 5)
.Select(o => new OrderEditViewModel
{
OrderId = o.OrderId,
ShippingDate = o.ShippingDate,
Remark = o.Remark,
Customer = new OrderEditCustomerViewModel
{
Name = o.Customer.Name,
City = o.Customer.City
}
})
.SingleOrDefault();
On the other hand, if you have a CustomerEditView
which allows editing customer information and displays the orders of the customer in a list, the ViewModel might be:
public class CustomerEditViewModel
{
public int CustomerId { get; set; }
[Required, StringLength(50)]
public string Name { get; set; }
[Required, StringLength(50)]
public string City { get; set; }
//...
public IEnumerable<CustomerEditOrderViewModel> Orders { get; set; }
}
public class CustomerEditOrderViewModel
{
[ReadOnly(true)]
public DateTime? ShippingDate { get; set; }
[ReadOnly(true)]
public string Remark { get; set; }
// ...
}
Here CustomerEditOrderViewModel
doesn't need a reference to the CustomerEditViewModel
and you can create the ViewModel from the database this way for example:
var customerEditViewModel = context.Customers
.Where(c => c.CustomerId == 8)
.Select(c => new CustomerEditViewModel
{
CustomerId = c.CustomerId,
Name = c.Name,
City = c.City,
Orders = c.Orders.Select(o => new CustomerEditOrderViewModel
{
ShippingDate = o.ShippingDate,
Remark = o.Remark
})
})
.SingleOrDefault();
The Customer(*)ViewModel
s and the Order(*)ViewModel
s 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 OrderViewModel
and the CustomerViewModel
disappears because you normally don't need such a bidirectional reference for your views.