How do I create a custom value injection to map my entity to my view model? Attempt included

廉价感情. 提交于 2019-12-06 13:17:58

Finally found the examples I needed. Sadly,despite all my searching I've only just now landed on these. That's no one's fault by my own; however, my foot is sore from how much I've been kicking it.

Pertinent URLS:

The documentation (RTFM) http://valueinjecter.codeplex.com/documentation

Flattening Example & Convention http://valueinjecter.codeplex.com/wikipage?title=flattening&referringTitle=Documentation

Unflattening Example & Convention http://valueinjecter.codeplex.com/wikipage?title=unflattening&referringTitle=Documentation

Solution to my issue:

The convention that must be used on the view model is that top level properties are not prefixed by their property name as it would exist on the Entity. So, in my class below where FirstName, LastName, and Id all exist as top level properties on my Person entity, they don't get prefixed in my view model class. The City, State, Zip, and Id for the Person.Address property do get prefixed.

Oddly enough, I thought of this solution while I was trying to implement my own injection. I got one working that went from Entity to ViewModel....just not the other way around.

public class PersonViewModelPrefixed
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Id { get; set; }
    public int AddressId { get; set; }
    public string AddressCity { get; set; }
    public string AddressState { get; set; }
    public string AddressZip { get; set; } 
}

public static void Main(string[] args)
{   
        Person defaultPerson = getDefaultPerson();
        PersonViewModelPrefixed defaultPrefixedVm = getDefaultPrefixedViewModel();

        //flatten - Entity to View Model
        PersonViewModelPrefixed pvm = Flatten(defaultPerson);

        //unflatten - View Model to Entity
        Person person2 = Unflatten(defaultPrefixedVm);  
    Console.ReadLine();
}       

//unflatten - View Model to Entity
private static Person Unflatten(PersonViewModelPrefixed personViewModel)
{
    Person p = new Person();
    p.InjectFrom<UnflatLoopValueInjection>(personViewModel);
    return p;
}

//flatten - Entity to View Model
private static PersonViewModelPrefixed Flatten(Person person)
{
    PersonViewModelPrefixed pvm = new PersonViewModelPrefixed();
    pvm.InjectFrom<FlatLoopValueInjection>(person);
    return pvm;
}

So, given these details, does any one have some suggestions on how to make the Flatten & Unflatten methods more generic? That's what I'll be working on next.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!