Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map fields in an object to another dynamically?

Tags:

c#

c#-4.0

I have 2 objects with attributes as the following:

Object 1:

Person

  • Name
  • Location
  • Age
  • Address

Object 2:

PersonRule

  • PersonName
  • PersonLocation
  • PersonAge

The PersonRule is driven by an UI, which sets a person rule(can set many as well), and the user says what name, location, age should be in a rule. This rule should be matched against a person if the person has the same value for the attributes.

I can do a simple equality check, however it's also possible that in the future a new attribute is added to person rule, something like a personaddress. Then I need to do a check whether the rule matches person by taking person address also into consideration.

Is there a way I can build something like match all attributes of personrule to person attributes, so that I don't need to make changes when a new attribute gets added to the rule? Of course this is assuming that the corresponding attribute is available in person object.

Thanks, -Mike

like image 454
Mike Avatar asked Feb 20 '23 06:02

Mike


1 Answers

You can use one of the available object-to-object mappers library like AutoMapper or EmitMapper. They will take care of copying data from Person instance to PersonRule instance that can be compared against another PersonRule instance. For example with EmitMapper your code might look like this:

var config = new DefaultMapConfig().MatchMembers((m1, m2) => "Person" + m1 == m2);
ObjectMapperManager.DefaultInstance
                   .GetMapper<Person, PersonRule>(config)
                   .Map(person, personRule);
like image 60
Sergey Rybalkin Avatar answered Mar 03 '23 00:03

Sergey Rybalkin