0

I have the following View Model:

namespace App.ViewModels
{
    public class PersonVM
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

...

Suppose I call a method from the controller to update a Person by sending a partial PersonVM object (some fields are set, some are null). So not all the properties of the passed in variable are set. Hence I want to loop the ones that do and update the ViewModel

//still in ViewModels namespace

public static void UpdatePerson(PersonVM p, DatabaseContext ctx){

 var person = ctx.People.Where(r => r.Id == person.Id).FirstOrDefault();

 for (var prop in p){
  ...
 }

}

How can I loop over each of the set properties?

Jebathon
  • 4,310
  • 14
  • 57
  • 108
  • Your properties are all ints. Ints if not given are 0. You have no way of knowing which one are deliberately set to 0 vs which ones are 0 because of "not set" by your vc chain. You could fiddle with nullables - or give a better example. There are plenty of questions about reflection if that is what you are after, search SO. There is no need for reflection here - you just test if a prop was set or is null and if set, update it, if not, leave it be. – Patrick Artner Feb 07 '18 at 13:46
  • If you want to loop over all properties of an object without knowing them in advance you'll need to use reflection. There are performance implications though. – Justinas Marozas Feb 07 '18 at 13:48
  • Well.. you can initialize them all to int.MaxValue in the ctor of PersonVM and use reflection to update the ones which are relevant by matching with int.MaxValue – Skyuppercut Feb 07 '18 at 13:49
  • @Skyuppercut and then you can't decide if its a really, reaaaallllly old person or unset ;) There is no need for reflection, he knows all the properties at this point in code. – Patrick Artner Feb 07 '18 at 13:50
  • @PatrickArtner My bad name was supposed to be a string – Jebathon Feb 07 '18 at 13:51
  • @PatrickArtner True. if he does, he doesn't need reflection. – Skyuppercut Feb 07 '18 at 13:57

0 Answers0