Note that there are some explanatory texts on larger screens.

plurals
  1. POAutomapper + EF4 + ASP.NET MVC - getting 'context disposed' error (I know why, but how to fix it?)
    primarykey
    data
    text
    <p>I have this really basic code in a MVC controller action. It maps an <code>Operation</code> model class to a very basic <code>OperationVM</code> view-model class . </p> <pre><code>public class OperationVM: Operation { public CategoryVM CategoryVM { get; set; } } </code></pre> <p>I need to load the complete list of categories in order to create a CategoryVM instance.<br> Here's how I (try to) create a <code>List&lt;OperationVM&gt;</code> to show in the view. </p> <pre><code>public class OperationsController : Controller { private SomeContext context = new SomeContext (); public ViewResult Index() { var ops = context.Operations.Include("blah...").ToList(); Mapper.CreateMap&lt;Operation, OperationVM&gt;() .ForMember( dest =&gt; dest.CategoryVM, opt =&gt; opt.MapFrom( src =&gt; CreateCatVM(src.Category, context.Categories) // trouble here ----------------^^^^^^^ ) ); var opVMs = ops.Select(op =&gt; Mapper.Map&lt;Operation, OperationVM&gt;(op)) .ToList(); return View(opVMs); } } </code></pre> <p>All works great first time I hit the page. The problem is, the mapper object is static. So when calling <code>Mapper.CreateMap()</code>, the instance of the current <code>DbContext</code> is saved in the closure given to CreateMap().</p> <p>The 2nd time I hit the page, the static map is already in place, still using the reference to the initial, now disposed, <code>DbContext</code>.</p> <p>The exact error is:</p> <pre><code>The operation cannot be completed because the DbContext has been disposed. </code></pre> <p>The question is: How can I make AutoMapper always use the <em>current</em> context instead of the initial one?</p> <p>Is there a way to use an "instance" of automapper instead of the static <code>Mapper</code> class? If this is possible, is it recommended to re-create the mapping every time? I'm worried about reflection slow-downs.</p> <p>I read a bit about custom resolvers, but I get a similar problem - How do I get the custom resolver to use the current context?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload