Given these classes that we want to map between:

public class GuiPerson
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
}

public class DomainPerson
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
}

To automatically create relations between properties with equal names, we simply write:

var mapping = new Mapping<DomainPerson, GuiPerson>();
mapping.AutoRelateEqualNames();

Now we can map between the types like this:

var domainPerson = new DomainPerson{FirstName = "Tore",LastName="TheCoder"};
var guiPerson = new GuiPerson();

mapping.Map(domainPerson, guiPerson);

Assert.Equal("Tore", guiPerson.FirstName);
Assert.Equal("TheCoder", guiPerson.LastName);

Unidirectional mapping

If you need to enforce that the mapping is only allowed in one direction, you simply override the autorelated result like this:

mapping = new Mapping<DomainPerson, GuiPerson>();
mapping.AutoRelateEqualNames(); // autorelate
mapping.RelateTowardsRight(domainperson => domainperson.LastName, guiperson => guiperson.LastName); //override

(What happens is that first AutoRelateEqualNames() will create a bidirectional relation between LastName. Then we override this by simply adding a relation between LastName that is TowardsRight.)

In this example we say that you are not allowed to map LastName back to the DomainPerson.

When you map to the guiPerson (TowardsRight), everything gets mapped:

domainPerson.FirstName = "Tore";
domainPerson.LastName = "TheCoder";

mapping.Map(domainPerson, guiPerson);

Assert.Equal("Tore", guiPerson.FirstName);
Assert.Equal("TheCoder", guiPerson.LastName);

But mapping back to the domainPerson (TowardsLeft), does not map LastName, just like we specified:

guiPerson.FirstName = "Tore";
guiPerson.LastName = "TheCoder";
domainPerson.FirstName = "-";
domainPerson.LastName = "-";

mapping.Map(guiPerson, domainPerson);

Assert.Equal("Tore", domainPerson.FirstName);
Assert.Equal("-", domainPerson.LastName);

Last edited Aug 8, 2009 at 6:46 AM by ToreVestues, version 5

Comments

No comments yet.