Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It is possible, but the setup is a bit complicated. I use this in my projects with help of Ninject for dependency injection. </p> <p>AutoMapper has concept of TypeConverters. Converters provide a way to implement complex operations required to convert certain types in a separate class. If converting Category to CategoryVM requires a database lookup you can implement that logic in custom TypeConverter class similar to this:</p> <pre><code>using System; using AutoMapper; public class CategoryToCategoryVMConverter : TypeConverter&lt;Category, CategoryVM&gt; { public CategoryToCategoryVMConverter(DbContext context) { this.Context = context; } private DbContext Context { get; set; } protected override CategoryVM ConvertCore(Category source) { // use this.Context to lookup whatever you need return CreateCatVM(source, this.Context.Categories); } } </code></pre> <p>You then to configure AutoMapper to use your converter:</p> <pre><code>Mapper.CreateMap&lt;Category, CategoryVM&gt;().ConvertUsing&lt;CategoryToCategoryVMConverter&gt;(); </code></pre> <p>Here comes the tricky part. AutoMapper will need to create a new instance of our converter every time you map values, and it will need to provide DbContext instance for constructor. In my projects I use Ninject for dependency injection, and it is configured to use the same instance of DbContext while processing a request. This way the same instance of DbContext is injected both in your controller and in your AutoMapper converter. The trivial Ninject configuration would look like this:</p> <pre><code>Bind&lt;DbContext&gt;().To&lt;SomeContext&gt;().InRequestScope(); </code></pre> <p>You can of course use some sort of factory pattern to get instance of DbContext instead of injecting it in constructors.</p> <p>Let me know if you have any questions.</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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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