2

Folks, I am mapping EF objects to simple Pocos using automapper in my service layer. I have certain entities that have many relationships in EF,but I want to restrict how much of this gets pulled back from the db. One of these entities would map to a database table but would have many relationships to other tables that would appear as entity collections in the generated model (EDMX).

So I have created a "shallow" poco for the entity which only has poco properties for the first level of properties in the entity, i.e. some integer Ids instead of associated collections/entity collections. I map in the following manner....

var simplepocoforentity= Mapper.Map(_readOnlyDb.Single<EfEntity>(x => x.Id== Id),
                                    new SimplPocoForEntity());

My question is.. because I am only mapping the entity to a simple poco here, can I be confident that EF will not try and query other non referenced data from the underlying db tables relationships when I do the mapping?

I know that I can investigate this via SQL Profiling, but I would appreciate any input befor going down that route. Thanks K.

1 Answer 1

2

It depends on the internal implementation of AutoMapper. I would assume that AutoMapper does not try to access the navigation properties of the entity (in which case lazy loading and an additional database query would kick in). I don't see a reason why AutoMapper should do this if you only map scalar properties. But who knows...

If you want to be on the safe side you could disable lazy loading temporarily:

try
{
    _readOnlyDb.ContextOptions.LazyLoadingEnabled = false;

    var simplepocoforentity = Mapper.Map(_readOnlyDb.Entities
        .Single(x => x.Id == Id), new SimplPocoForEntity());

    // ...
}
finally
{
    _readOnlyDb.ContextOptions.LazyLoadingEnabled = true;
}

As a side note: Be aware that you load the full entity into the context with this approach. After that the mapping happens. Potentially you load more columns from the database than you really need (perhaps not in your special case here). In general I would do the mapping with a projection which ensures that the database only queries the columns which are needed:

var simplepocoforentity = _readOnlyDb.Entities
    .Where(e => e.Id == Id)
    .Select(e => new SimplPocoForEntity
    {
        PocoProperty1 = e.EntityProperty1,
        PocoProperty2 = e.EntityProperty2,
        PocoProperty3 = e.EntityProperty3
        // etc.
    })
    .Single();

With this approach no lazy loading would happen at all because you don't load the entity but directly the PocoForEntity from the database.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.