1

To extend (What to do when model is exactly the same as viewmodel with a specific inquiry to coding practice....

...in other words, what is best mapping solution when a domain model contain the same properties as the needed viewmodel?

For whatever reason this happens more frequently than I expect, maybe because the domain models tend to have several navigation properties. Nearly 'it all' ends up in the view.

Is there an automapper shortcut, inheritance strategy or maybe a Linq expression to perform the direct mapping?

I've experimented a little with inheritance which gets weird quickly and the Automapper's 'Mapping by naming convention' that has serious limitations especially for complex types.

Except meeting the need for data annotations, I'm leaning towards using the domain model in the views and performing validation in the view. So the lack of a mapping method is pushing me towards coding in an 'anti-pattern' that I don't really want.

Community
  • 1
  • 1
Stephan Luis
  • 911
  • 1
  • 9
  • 24

1 Answers1

1

It depends on the content of your models but you can try converting your object to Json and then converting it back to the target type:

    public class SourceEntity
    {
        public string Name { get; set; }
        public DateTime StartDate { get; set; }
    }
    public class TargetEntity
    {
        public string Name { get; set; }
        public DateTime StartDate { get; set; }
    }
    public void Sample()
    {
        SourceEntity sourceEntity = new SourceEntity { Name = "Test name", StartDate = DateTime.Now.AddDays(-3) };
        TargetEntity targetEntity = JObject.FromObject(sourceEntity).ToObject<TargetEntity>();
    }

You will need to add Newtonsoft.Json to your project.

This will convert complex properties and child collections too but will struggle with interfaces and derived classes in the target type.

bib1257
  • 325
  • 2
  • 7
  • A neat idea ... I had a look at Newtonsoft.Json for Ajax calls and ended up using a .serialiseArray method instead. Was surprised by the limitations of the .net Json serialiser. Will Newtonsoft 'swollow' large class structures? – Stephan Luis Oct 19 '16 at 22:31
  • Newtonsoft has its limitations but in my experience object size is not one of them. How large is "large"? We use Json for structures with hundreds of fields and have not seen any performance issues so far. – bib1257 Oct 19 '16 at 22:38
  • By the way, this will also convert "similar" models. Any fields in the source model that do not exist in the target model will be ignored so your view model can have less data than your domain model – bib1257 Oct 19 '16 at 22:47