Question

I wonder if it is really needed to use some object-to-object mapper, when mapping entity framework entities to ViewModels. Samples around generally shows 1-entity mapping to 1-viewmodel. But real-life is usually different; because we generally need to join multiple tables and choose some columns from each. (I use POCO entities and ASPNET MVC) Here is what i always use to map my linq query result to ViewModels.

public List<MyViewModel> GetSomeDataForView(string filter1)
    {
        using (MyEntities context = GetMyEntites())
        {
            var query = (from t1 in context.Table1
                         join t2 in context.Table2 on t2.Table1Id equals t1.Id
                         join t3 in context.Table3 on t3.Table2Id equals t2.Id
                         where t1.FilterColumn=filter1
                         select new MyViewModel
                         {
                             Property1 = t1.Column1,
                             Property2 = t1.Column2,
                             Property3 = t2.Column1,
                             Property4 = t3.Column1
                         });

            return query.ToList();
        }
    }
Was it helpful?

Solution

No, it is not really needed. Whatever works for you and fulfils your requirements is good enough.

Automapper and similar solutions allow you to pull out mapping logic to separate layer and automate it a bit. Sometimes this is a benefit and sometimes not. Everything depends on the context.

OTHER TIPS

Not in the example you show, which does a custom projection and joining. Typically it would look like this in my projects:

using (MyEntities context = GetMyEntites())
{
    var query = context.Table1
        .Where(t1 => t1.FilterColumn == filter1)
        Project().To<MyViewModel>();

    return query.ToList();
}

See more information here: https://github.com/AutoMapper/AutoMapper/wiki/Queryable-Extensions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top