Kliver Max
Kliver Max

Reputation: 5299

How to minimize code in viewmodel to object conversion?

I have a objects in my context:

abstract public partial class MyAbstractObject
{
    public int Id{set;get;}
    public string Name{set;get;}
}

public partial class MyChildObject: MyAbstractObject
{
    public string Details {set;get;} 
}

And i have a view models for ths objects:

public class MyAbstractViewModel
{
    public int Id{set;get;}
    public string Name{set;get;}
}

public class MyChildViewModel: MyAbstractViewModel
{
    public string Details {set;get;} 
}

Now for convert my view models to objects i use something like:

public MyChildObject MakeChildObject(MyChildViewModel vm)
{
  var child = new  MyChildObject();
  child.Id = vm.Id;
  child.Name = vm.Name;
  child.Details= vm.Details;

  return child;
 }

My problem in MyAbstractObject properties. If i have a several child objects i create a MakeChildObject methods for each child object. And all this methods have a same code lines for MyAbstractObject properties:

  child.Id = vm.Id;
  child.Name = vm.Name;

How can i minimize my code?

Upvotes: 1

Views: 91

Answers (3)

petchirajan
petchirajan

Reputation: 4352

Try the below code sample to solve your issue.

public class MyAbstractViewModel
{
    public int Id{set;get;}
    public string Name{set;get;}

  public void MakeChildObject(MyAbstractViewModel vm, MyAbstractObject child)
  {
    child.Id = vm.Id;
    child.Name = vm.Name;
  }
}

public class MyChildViewModel: MyAbstractViewModel
{
  public string Details {set;get;} 

  public MyChildObject MakeChildObject(MyChildViewModel vm)
  {
    var child = new  MyChildObject();
    this.MakeChildObject(this, child);

    child.Details= vm.Details;

    return child;
  }
}

Upvotes: 1

doorstuck
doorstuck

Reputation: 2308

Consider if AutoMapper can be used in your case. It will automatically map objects of different types based on property names. It might save you the time of writing all the mapping code yourself.

https://github.com/AutoMapper/AutoMapper

You will then bootstrap the mapper like so:

Mapper.CreateMap<MyChildViewModel, MyChildObject>();

And instead of your method MakeChildObject you will use the following:

MyChildObject vmMapped = Mapper.Map<MyChildViewModel>(vm);

Upvotes: 2

Hintham
Hintham

Reputation: 1086

Have a look at automapper http://automapper.org/

It will automatically map similar named properties. It also includes a feature to map base objects. See also This post

Upvotes: 0

Related Questions