Mike
Mike

Reputation: 3284

How to map fields in an object to another dynamically?

I have 2 objects with attributes as the following:

Object 1:

Person

Object 2:

PersonRule

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

Upvotes: 4

Views: 6446

Answers (2)

Sergey Rybalkin
Sergey Rybalkin

Reputation: 3026

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);

Upvotes: 8

dani herrera
dani herrera

Reputation: 51705

It seems that you are looking for reflection, see this sample question:

How to get the list of properties of a class?

Upvotes: 0

Related Questions