griegs griegs - 1 year ago 210
C# Question

Automapper not ignoring properties with an error

We have a complex object User that contains a bunch of lists of other objects.

List<User> Subordinates {get; set;}

When we run the code, it's quite acceptable for some of the properties to be in error because the connection to the database has been closed and we didn't get the say Subordinates.

In AutoMapper I am getting an error when trying to map the User class to another Class.

So the error in the Subordinates property is;

'((System.Data.Entity.DynamicProxies.User_26F7582000F06E0D5B307573194E69014E40D1C586E95D4E4932757C1F4DE360)((System.Data.Entity.DynamicProxies.WorkflowTask_DEDE69BC0D3CAFD0CCDA62406BC48A7A7CCBD5E8B13369FF5E761B64348A767C)thisTask).User).Subordinates' threw an exception of type 'System.ObjectDisposedException'

And the error that AutoMapper is throwing is;

{"Error mapping types.\r\n\r\nMapping types:\r\nWorkflowTask -> jsonTask\r\nDataRepository.WorkflowTask -> Tasks.Models.jsonTask\r\n\r\nType Map configuration:\r\nWorkflowTask -> jsonTask\r\nDataRepository.WorkflowTask -> Tasks.Models.jsonTask\r\n\r\nProperty:\r\nUser"}

And then in the InnerException;

{"Error mapping types.\r\n\r\nMapping types:\r\nUser -> jsonUser\r\nDataRepository.User -> Tasks.Models.jsonUser\r\n\r\nType Map configuration:\r\nUser -> jsonUser\r\nDataRepository.User -> Tasks.Models.jsonUser\r\n\r\nProperty:\r\nSubordinates"}

I just need AutoMapper to ignore those properties that are in error.

Answer Source

The root cause is the data is lazy loaded into your entities, usually inside a using(var context = new MyDbContext()) block, and AutoMapper tries to map unloaded properties outside the context block, triggers the loading, hence the System.ObjectDisposedException because the context is already disposed.

What you need to do is NOT ignoring the properties that failed to load, but make sure all properties are correctly loaded before being mapped. I suggest you read this guidance, it shows how to put controllers, entities and dbcontext into correct layers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download