简体   繁体   中英

Easy binding model to viewmodel

I currently have a databasemodel student for example:

class Student
{
    public string fname { get; set; }
    public string lname { get; set; }
    public string address { get; set; }
}

and for editing

class StudentEditViewModel
{
    public StudentEditViewModel(Student s)
    {
        fname = s.fname;
        lname = s.lname;
        address = s.address;
    }

    [Display(Name = "First name")]
    [Required(ErrorMessage = "First name is required")]
    public string fname { get; set; }
    public string lname { get; set; }
    public string address { get; set; }
}

in my full code there are a lot more properties, now i am getting pretty tired of typing everything 5 times, The model, the view model properties, the init of the VM, specifying these things in the view, when saving again, converting the vm to the model and then saving.

For reasons with still using Nhibernate i cant directly use the model as viewmodel, but isnt there a more effecient way that not everything has to be types 5 times?

You could store a local reference to the Student inside the ViewModel and just get/set the model iteself in the properties. For example:

class StudentEditViewModel
{
    private Student mStudentModel;

    public StudentEditViewModel(Student s)
    {
       mStudentModel = s;
    }

    [Display(Name = "First name")]
    [Required(ErrorMessage = "First name is required")]
    public string firstname 
    {
        get
        {
            return mStudentModel.fname;
        }
        set
        {
            // Check if changed
            if(mStudentModel.fname != value)
            {
               mStudentModel.fname = value;
               // NotifyPropertyChange
            }
        }
    }
    // same for other properties
}

Otherwise use Automapper as @abatishchev suggested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM