Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6163137
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T21:46:26+00:00 2026-05-23T21:46:26+00:00

I’m trying to ease the use of AutoMapper in my project, by implementing an

  • 0

I’m trying to ease the use of AutoMapper in my project, by implementing an extension method .ToViewModel(). Basically, it will just be a wrapper around the standard call, but I often find myself annoyed about how much I must type each time I want to map something. Compare the two:

var viewModel = Mapper.Map<DomainEntityType, ViewModelType>(entity);
// or...
var viewModel = entity.ToViewModel();

I feel number two would be sweet =) I’ve let all my entities extend IEntity, and all viewmodels (that correspond to an entity) extend IViewModel<IEntity>, and written the following extension method:

public static IViewModel<TEntity> ToViewModel<TEntity>(this TEntity entity) 
    where TEntity : IEntity
{
    return Mapper.Map<TEntity, IViewModel<TEntity>>(entity);
}

However, I’m unable to make this fly.

The following NUnit test makes an attempt at testing this (although I’m unsure if Assert.AreEqual really tests what I want – does it require reference equality? If so, how do I test “are equivalent”?). The test fails with the message

Expected: <Castle.Proxies.IViewModel`1Proxy>
But was:  <Castle.Proxies.IViewModel`1Proxy>
[Test]
public void DomainEntityTypeMapsViewModelType()
{
    var entity = new DomainEntityType();
    var oldskool = Mapper.Map<DomainEntityType, IViewModel<Entity>>(entity);
    var extension = inspectionObject.ToViewModel();

    Assert.AreEqual(oldskool, extension);
}

Except for the fact that my test might be testing the wrong thing, am I missing something fundamental about how AutoMapper works? Will AutoMapper ever be able to correctly map something to an interface? (I do have a class, EntityViewModel, that implements ViewModel<Entity>, but I haven’t told AutoMapper specifically about it…)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T21:46:27+00:00Added an answer on May 23, 2026 at 9:46 pm

    I finally managed to do this in a generic way. It required some tweaking of my objects, but here’s what I did:

    Since before, most of my entities inherit from Entity<TId> (usually Entity<int>, but the id could potentially be another data type, for example a GUID), which in turn implements the interface IEntity<TId> (with a single property public TId ID {get;}). The few entities that don’t inherit Entity<TId>, at least implement IEntity<TId>.

    I created a new class, which overrides Equals and GetHashcode:

    public class ViewModel<TEntity, TId> : IEntity<TId>
        where TEntity : IEntity<TId>
    {
        public TId ID { get; set; }
    
        public override bool Equals(object obj)
        {
            var viewModel = obj as ViewModel<TEntity, TId>;
            return viewModel != null && Equals(viewModel);
        }
    
        public bool Equals(ViewModel<TEntity, TId> other)
        {
            return ID.Equals(other.ID);
        }
    
        public override int GetHashCode()
        {
            // Not only returning ID.GetHashCode() in case I want to add more
            // properties later...
            var hash = 7;
            hash = (hash * 17) + ID.GetHashCode();
    
            return hash;
        }
    }
    

    Now, all my viewmodels (and editmodels) inherit from this class:

    public class EntityViewModel : ViewModel<EntityType, int>
    {
        // data properties
    }
    

    I could then extend my entities and viewmodels with the following extension methods:

    public static TViewModel To<TViewModel>(this IEntity entity) where TViewModel : class
    {
        return Mapper.Map(entity, entity.GetType(), typeof(TViewModel)) as TViewModel;
    }
    
    public static TEntity ToEntity<TEntity, TId>(this ViewModel<TEntity, TId> viewmodel) where TEntity : class, IEntity<TId>
    {
        return Mapper.Map(viewmodel, viewmodel.GetType(), typeof(TEntity)) as TEntity;
    }
    

    A key concept to make this work was to abandon the generic overloads of .Map, since I didn’t know the exact types I wanted to map to and from at compile time.

    I can now move back and forth between the types using the following syntax:

    var entity = new EntityType();
    var viewmodel = entity.To<EntityViewModel>();
    
    var backagain = viewmodel.ToEntity();
    

    which I am quite content with, since my original goal of abstracting away AutoMapper from the implementation in the controllers have been well achieved.

    You’ll notice that there is a non-generic version of IEntity too – that’s just an empty interface, which IEntity<T> inherits from. This might be considered dull, but there’s a simple reason not to use the generic version: if you do, you’ll also have to specify it as a type argument to the extension method. You’ll end up with entity.To<EntityViewModel,int>() instead of the above syntax, since inferring type arguments is an all-or-nothing affair.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I want use html5's new tag to play a wav file (currently only supported
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.