Answer the question
In order to leave comments, you need to log in
What is the most optimal approach to create a ViewModel?
Dear users,
I comprehend the delights of the ASP.NET MVC framework together with the Entity Framework. Uses the DataBase-First design approach.
Entity Framework automatically generates models for me, with each model described in a partial class (probably not just like that?).
The question is the following: there is a simple model for ordering a car - Order. Let's simplify this entity to two properties:
-Car brand (Car)
-Customer name (CustomerName)
We get the generated class:
public partial class Order
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public string CustomerName { get; set; }
public string Car{ get; set; }
}
public class OrderItemViewModel
{
public ItemToolboxViewModel Toolbox { get; set; }
public Data.Order Item { get; set; } // это ссылка на доменную модель
}
List<SelectListItem>
. In this case, the model looks like:public class OrderItemCreateViewModel
{
public ItemCreateToolboxViewModel Toolbox { get; set; }
public OrderItemCreateModel Item { get; set; }
}
public class OrderItemCreateModel
{
public string CustomerName { get; set; }
public string Car{ get; set; } // используется для байндинга значения во View
public List<SelectListItem> Cars{ get; set; } // используется для заполнения списка автомобилей в DropDownFor
}
OrderItemCreateViewModel.Item
I cannot send it to Context.Orders.Add()
. You have to define a new Order domain model object and initialize the values with properties fromOrderItemCreateViewModel.Item
Answer the question
In order to leave comments, you need to log in
I guess I didn’t quite understand something ... ViewModel denotes models that will go into a view to display information there. Why encapsulate another in one viewmodel? These models basically contain only the necessary information for the view and no logic. If you don't need car lists in the domain model, then you shouldn't make them there. It is necessary to initialize the viewmodel with the necessary list and give this model to the view. The viewmodel is initialized either manually by the domain model or by the automapper.
I think you need to add a directory of car models and create a one-to-many relationship, something like this...
public partial class Order
{
public string CustomerName { get; set; }
public id CarLabelId { get; set; }
public CarLabel CarLabel { get; set; }
}
public class CarLabel
{
public int Id { get; set; }
public string NameCar { get; set; }
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question