Do viewmodels need keys?

前端 未结 2 1926
孤城傲影
孤城傲影 2021-02-10 12:29

I have my view model :

namespace projInterview.Models
{
    public class QuestionViewModel
    {
        public piQuestion Question { get; set; }
        public          


        
2条回答
  •  轮回少年
    2021-02-10 13:19

    Wait wait wait. A view model has absolutely nothing to do with an Entity framework context. It should not be associated with it. What you seem to have right now is that db.piQuestions is an IQueryable which is an absolutely wrong thing to do. A view model doesn't know anything about EF and EF doesn't know anything about view models.

    NEVER map your view models to any database or EF stuff. What you put as IQueryable properties to your DBContext are your Domain Models. Those are the models that are bound to your database tables.

    Then in your controller action you make one or more calls to your database (DbContext) in order to retrieve one or more of those domain models. Then you map (copy the properties) of those domain models to a single view model. Finally you pass the view model to the view.

    Also as a side remark, view models usually have default constructors. You don't need those specific constructors taking parameters. That will just make the default model binder insane if you attempt to have such view model as parameter to a controller action.

    So to conclude: view models do not have any keys. They should not even know what a key is. A key is something specific to your Data Access Layer that is to say to your Domain Models.

提交回复
热议问题