-1

I follow this tutorial on WPF MVVM

https://metanit.com/sharp/wpf/21.2.php

It's in russian, but basically the viewmodel contains a list of Phone objects and the tutorial teaches how to implement Add/Remove/Delete Commands to the list of Phone with writing the changes to the database. Here's the EditCommand Command:

public RelayCommand EditCommand
{
    get
    {
        return editCommand ??
            (editCommand = new RelayCommand((selectedItem) =>
            {
                if (selectedItem == null) return;
                Phone phone = selectedItem as Phone;
 
                Phone vm = new Phone()
                {
                    Id = phone.Id,
                    Company = phone.Company,
                    Price = phone.Price,
                    Title = phone.Title
                };
                PhoneWindow phoneWindow = new PhoneWindow(vm);
 
                if (phoneWindow.ShowDialog() == true)
                {
                    phone = db.Phones.Find(phoneWindow.Phone.Id);
                    if (phone != null)
                    {
                        phone.Company = phoneWindow.Phone.Company;
                        phone.Title = phoneWindow.Phone.Title;
                        phone.Price = phoneWindow.Phone.Price;
                        db.Entry(phone).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
        }));
    }
} 

Here, author copies properties one by one from selectedItem to the vm object and later from phoneWindow to the database model.

The problem is, in the project I'm working on, instead of a simple class Phone I use complex class with many nested types and nested lists. Do I have to copy them all by hand 2 times? How can I automate it?

Igor Cheglakov
  • 525
  • 5
  • 11
  • _"Do I have to copy them all by hand"_ -- maybe, maybe not. That depends on the objects, and your question lacks specific details along those lines. If they are mutable objects and you want to capture the current state of the object, keeping the copy exactly as-is even if the other changes, you'll need to deep-clone the object. See duplicate. If you want the copy to reflect changes, no copy is needed, just use the same reference. Likewise if the objects are immutable, you don't need to worry because there won't ever be a change to the object. – Peter Duniho Feb 17 '21 at 01:52

1 Answers1

0

To easily map one object to another you can use a mapper library to do the heavy work for you, like AutoMapper.

All you have to do is configure the mappings you will need during startup:

var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDto>());

Then call Map() on the object:

var mapper = config.CreateMapper();
// or
var mapper = new Mapper(config);
OrderDto dto = mapper.Map<OrderDto>(order);

More info here

LoRdPMN
  • 512
  • 1
  • 5
  • 18