Search code examples
asp.net-mvcmodelviewmodel

HowTo fetch data to viewmodel the quickest way


I have a simple problem with my site.
Inside my site, I'm using two different models, with some identical named fields. Because of collision, I have to give them unique names and for not loosing the modelbinding, I decided to use viewModels.

So I have a Model like this:

namespace MySite.Models
{
  public class Function : BaseEntity
  {
    //Beziehung zur Funktionsgruppe
    [Required]
    [Display(Name = "Übergeordnete Funktion")]
    public int FunctionGroupId { get; set; }
    public virtual FunctionGroup FunctionGroup { get; set; }

    [Required]
    [StringLength(200)]
    [Display(Name = "Bezeichnung")]
    public string Name { get; set; }
  }
}

And I have a new ViewModel like this:

namespace MySite.ViewModels
{
  public class FunctionViewModel
  {
    //Properties of BaseEntity
    public int F_Id { get; set; }
    [Display(Name = "Erstellt")]
    public string F_Created { get; set; }
    [Display(Name = "Bearbeitet")]
    public string F_LastChange { get; set; }
    [Display(Name = "Bearbeiter")]
    public string F_ByUser { get; set; }

    //Beziehung zur Funktionsgruppe
    [Required]
    [Display(Name = "Übergeordnete Funktion")]
    public int F_FunctionGroupId { get; set; }
    public virtual FunctionGroup F_FunctionGroup { get; set; }

    [Required]
    [StringLength(200)]
    [Display(Name = "Bezeichnung")]
    public string F_Name { get; set; }
  }
}

Now my Question is, is there a way to automatically fetch the data of the corresponding model, while loading the ViewModel?

Something like a kind of function directly inside the { get; set; }?
Actually I load field by field form the model into the ViewModel.

Hope that I could have described Right, what I'd like to do.

Carsten


Solution

  • You can use Automapper for mapping or getting your data from Model to ViewModel or vice-versa. It will be hard for you to map/configure if your name of your property is different so have the same name in view model as well. (If possible)