0

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

User
  List<User> Subordinates {get; set;}
  etc....

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.

griegs
  • 22,624
  • 33
  • 128
  • 205

1 Answers1

2

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.

Cheng Chen
  • 42,509
  • 16
  • 113
  • 174
  • Thanks for that and yeah I'd come to the same conclusion. The issue I have is that I don't "need" to load the entities and I certainly don't want to pass all that back to the view. I just want to pass back what is needed and in this case the Subordinates is not required by the view. Just trying to reduce the amount that is passed back. Thanks for the link, I'll give that a read also. – griegs Aug 19 '16 at 03:21
  • @griegs If the properties are not needed in a view, you should remove them from the corresponding view model. If one view needs them but another view doesn't, you should create different view models instead of sharing one view model. – Cheng Chen Aug 19 '16 at 03:24
  • Yeah good point! Thanks Danny, that's what I'll do. I was going down a very dark path with this and just needed someone to shine a light on that stupidity. Thanks. +1 – griegs Aug 19 '16 at 03:28