### Install Mapster Async Package Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/packages/Async.md Use this NuGet command to install the Mapster.Async package. ```nuget PM> Install-Package Mapster.Async ``` -------------------------------- ### Install Mapster.Tool Source: https://github.com/mapstermapper/mapster/wiki/Mapster.Tool Installs the Mapster.Tool globally. Ensure you have a dotnet-tools.json file if you skip the first step. ```bash #skip this step if you already have dotnet-tools.json dotnet new tool-manifest dotnet tool install Mapster.Tool ``` -------------------------------- ### Install Mapster.JsonNet Package Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/packages/Json.net.md Use the NuGet Package Manager Console to install the Mapster.JsonNet package. ```powershell PM> Install-Package Mapster.JsonNet ``` -------------------------------- ### Install FastExpressionCompiler Package Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/packages/FastExpressionCompiler.md Use the NuGet Package Manager Console to install the FastExpressionCompiler package. ```nuget PM> Install-Package FastExpressionCompiler ``` -------------------------------- ### Install Mapster.Tool Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/tools/mapster-tool/Mapster-Tool-Overview.md Installs the Mapster.Tool command-line utility. Ensure you have a dotnet-tools.json file or create one using 'dotnet new tool-manifest'. ```bash dotnet new tool-manifest dotnet tool install Mapster.Tool ``` -------------------------------- ### Install Mapster.Core Package Source: https://github.com/mapstermapper/mapster/wiki/Mapster.Tool Installs the Mapster.Core NuGet package for lightweight dependency. Use this if you don't need advanced configuration. ```powershell PM> Install-Package Mapster.Core ``` -------------------------------- ### Install Mapster Dependency Injection Package Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/packages/Dependency-Injection.md Use the Package Manager Console to install the Mapster.DependencyInjection NuGet package. ```nuget PM> Install-Package Mapster.DependencyInjection ``` -------------------------------- ### Install ExpressionDebugger Package Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/packages/ExpressionDebugging.md Install the ExpressionDebugger NuGet package using the Package Manager Console. ```nuget PM> Install-Package ExpressionDebugger ``` -------------------------------- ### Install Mapster with .NET CLI Source: https://github.com/mapstermapper/mapster/blob/master/README.md Use this command to add the Mapster package to your .NET project. ```bash dotnet add package Mapster --project ``` -------------------------------- ### Clone Global Settings Source: https://github.com/mapstermapper/mapster/wiki/Config-instance Create a new configuration instance by cloning the global settings. This is useful for starting with default configurations and then modifying them. ```csharp var newConfig = TypeAdapterConfig.GlobalSettings.Clone(); ``` -------------------------------- ### Install Mapster.Immutable Package Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/packages/Immutable.md Install the Mapster.Immutable NuGet package using the Package Manager Console. ```nuget PM> Install-Package Mapster.Immutable ``` -------------------------------- ### Install ExpressionTranslator Package Source: https://github.com/mapstermapper/mapster/wiki/TextTemplate Use the Package Manager Console to install the ExpressionTranslator NuGet package. ```powershell PM> Install-Package ExpressionTranslator ``` -------------------------------- ### Install Mapster with NuGet CLI Source: https://github.com/mapstermapper/mapster/blob/master/README.md Use this command to install the Mapster package using the NuGet Package Manager Console. ```powershell Install-Package Mapster ``` -------------------------------- ### Build Adapter with Runtime Parameters Source: https://github.com/mapstermapper/mapster/wiki/Setting-values When passing runtime values, use the `BuildAdapter` method and `AddParameters` to supply the necessary parameters. This example adds a 'user' parameter before adapting to type `Dto`. ```csharp var dto = poco.BuildAdapter() .AddParameters("user", this.User.Identity.Name) .AdaptToType(); ``` -------------------------------- ### Install Mapster Package Source: https://github.com/mapstermapper/mapster/wiki/Mapster.Tool Installs the full Mapster NuGet package, which includes TypeAdapterConfig for advanced configuration. ```powershell PM> Install-Package Mapster ``` -------------------------------- ### Generate Mapper from Interface Source: https://github.com/mapstermapper/mapster/wiki/Interface-base-Code-generation Annotate your interface with `[Mapper]` for the tool to pick it up for generation. This is a basic example of an interface for mapping. ```csharp [Mapper] public interface IProductMapper { ProductDTO Map(Product customer); } ``` -------------------------------- ### Install Mapster EF6 Package Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/packages/EF-6-and-EF-Core.md Use this NuGet command to install the Mapster package for Entity Framework 6 support. ```nuget PM> Install-Package Mapster.EF6 ``` -------------------------------- ### Install Mapster.EFCore Package Source: https://github.com/mapstermapper/mapster/wiki/EF-6-&-EF-Core Install the Mapster.EFCore NuGet package for EF Core integration. Ensure compatibility with your EF Core version. ```powershell PM> Install-Package Mapster.EFCore ``` -------------------------------- ### Open Generics Mapping Configuration Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/configuration/Configuration.md Configure mappings for generic types by providing the generic type definition to `ForType`. This example maps the 'value' property to 'Value'. ```csharp TypeAdapterConfig.GlobalSettings.ForType(typeof(GenericPoco<>), typeof(GenericDto<>)) .Map("value", "Value"); ``` -------------------------------- ### Step-Into Debugging with File Emission Source: https://github.com/mapstermapper/mapster/wiki/Debugging After configuring file emission, you can step into mapping functions, similar to the general debugging setup, but specifically for VS Mac compatibility. ```csharp var dto = poco.Adapt(); //<-- you can step-into this function!! ``` -------------------------------- ### Dynamic Outputs and Namespaces via csproj Source: https://github.com/mapstermapper/mapster/wiki/Mapster.Tool Example of using '-n' for namespace and '-b' for base namespace in Mapster.Tool commands within a csproj target for structured code generation. ```xml ``` -------------------------------- ### Automatic Mapster Compilation Source: https://github.com/mapstermapper/mapster/wiki/Config-validation-&-compilation Mapster automatically compiles mappings upon first usage. This example shows the typical usage of `Adapt`. ```csharp var result = poco.Adapt(); ``` -------------------------------- ### Get Default Settings Source: https://github.com/mapstermapper/mapster/wiki/Home Retrieves the default settings applied to all type pairs. Use this for global configurations. ```csharp config.Default ``` -------------------------------- ### Custom Mapping with IMapFrom Interface Source: https://github.com/mapstermapper/mapster/wiki/Mapping-Configuration-With-IMapFrom-Interface Implement the IMapFrom interface and define a custom mapping configuration within the destination class. This example shows how to parse a string value to an integer during mapping. ```csharp public class InheritedDestinationModel : IMapFrom { public string Type { get; set; } public int Value { get; set; } public void ConfigureMapping(TypeAdapterConfig config) { config.NewConfig() .Map(dest => dest.Value, source => int.Parse(source.Value)); } } ``` -------------------------------- ### Setup Async Mapping with AfterMappingAsync Source: https://github.com/mapstermapper/mapster/wiki/Async Configure asynchronous operations to run after a mapping is completed. This is useful for fetching related data or performing side effects asynchronously. Ensure UserManager is available via MapContext.Current.GetService. ```csharp config.NewConfig() .AfterMappingAsync(async (poco, dto) => { var userManager = MapContext.Current.GetService(); var user = await userManager.FindByIdAsync(poco.UserId); dto.UserName = user.Name; }); ``` -------------------------------- ### Configure Mapster Code Generation in csproj Source: https://context7.com/mapstermapper/mapster/llms.txt Add a target to your csproj file to automatically run Mapster for code generation after the build process. Ensure Mapster.Tool is installed. ```xml ``` -------------------------------- ### Compute Full Name from First and Last Name Source: https://github.com/mapstermapper/mapster/wiki/Setting-values Use the `Map` method to define logic for computing a destination property from source properties. This example computes the `FullName` from `FirstName` and `LastName`. ```csharp TypeAdapterConfig.NewConfig() .Map(dest => dest.FullName, src => src.FirstName + " " + src.LastName); ``` -------------------------------- ### Custom Name Matching with Replacement Source: https://github.com/mapstermapper/mapster/wiki/Naming-convention Implement custom rules for name matching by replacing specific characters or patterns in source member names. This example replaces foreign letters like 'Ä' with their basic ASCII equivalents. ```csharp TypeAdapterConfig.NewConfig() .NameMatchingStrategy(NameMatchingStrategy.ConvertSourceMemberName(name => name.Replace("Ä", "A")); ``` -------------------------------- ### Map with Runtime Parameter for Creator Source: https://github.com/mapstermapper/mapster/wiki/Setting-values Pass runtime values, such as the current user's identity, into the mapping process using `MapContext.Current.Parameters`. This example maps the `CreatedBy` property using a parameter named 'user'. ```csharp TypeAdapterConfig.NewConfig() .Map(dest => dest.CreatedBy, src => MapContext.Current.Parameters["user"]); ``` -------------------------------- ### Apply Rule-Based Ignore Setting for Same Source and Destination Types Source: https://github.com/mapstermapper/mapster/wiki/Configuration Use the When method in GlobalSettings to apply conditional mapping rules. This example ignores the 'Id' property when the source and destination types are identical. ```csharp TypeAdapterConfig.GlobalSettings.When((srcType, destType, mapType) => srcType == destType) .Ignore("Id"); ``` -------------------------------- ### Basic Projection to DTOs with ProjectToType Source: https://context7.com/mapstermapper/mapster/llms.txt Use ProjectToType() to generate efficient SQL SELECT statements for DTOs in Entity Framework queries. Ensure Mapster.EFCore is installed. This avoids less efficient in-memory mapping. ```csharp // Install: dotnet add package Mapster.EFCore // Basic projection - generates efficient SELECT statement using (var context = new AppDbContext()) { // Mapster generates: SELECT Id, Name, Email FROM Customers WHERE ... var customerDtos = context.Customers .Where(c => c.IsActive) .ProjectToType() .ToList(); // Without projection (less efficient): // var customers = context.Customers.Where(c => c.IsActive).ToList(); // var dtos = customers.Adapt>(); // Maps in memory } ``` -------------------------------- ### Create New Configuration Instance Source: https://github.com/mapstermapper/mapster/wiki/Home Instantiate a new configuration object. This allows for isolated configuration settings. ```csharp var config = new TypeAdapterConfig() ``` -------------------------------- ### Separate Configuration and Mapping Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/configuration/Config-location.md Avoid recompiling configuration by separating it from mapping calls. Place configuration in entry points like `Main`, `Global.asax.cs`, `Program.cs`, or `Startup.cs`. ```csharp config.ForType().Ignore("Id"); var dto1 = poco1.Adapt(config); config.ForType().Ignore("Id"); //<--- Exception occurred here, because config was already compiled var dto2 = poco2.Adapt(config); ``` ```csharp // Application_Start in Global.asax.cs config.ForType().Ignore("Id"); ``` ```csharp // in Controller class var dto1 = poco1.Adapt(config); var dto2 = poco2.Adapt(config); ``` -------------------------------- ### Mapper Instance for Dependency Injection Source: https://github.com/mapstermapper/mapster/wiki/Home Shows how to create and use a `Mapper` instance, typically for dependency injection scenarios. ```APIDOC ## Mapper Instance Usage ### Description Illustrates creating a `Mapper` instance and performing mappings using it, suitable for dependency injection. ### Methods - `IMapper mapper = new Mapper()`: Creates a new instance of the `Mapper`. - `mapper.Map(src)`: Maps a source object to a new destination object of type `Dest` using the mapper instance. - `mapper.Map(src, dest)`: Maps a source object to an existing destination object using the mapper instance. ### Links - Mappers: [https://github.com/MapsterMapper/Mapster/wiki/Mappers](https://github.com/MapsterMapper/Mapster/wiki/Mappers) ``` -------------------------------- ### Configuration with Attributes Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/configuration/Config-location.md Configure mappings directly on POCO classes using the `AdaptTo` attribute for concise, attribute-based configuration. ```csharp [AdaptTo(typeof(StudentDto), PreserveReference = true)] public class Student { ... } ``` -------------------------------- ### Mapster Mapper Instance Source: https://github.com/mapstermapper/mapster/blob/master/docs/api/Reference.md Shows how to create and use a Mapster IMapper instance, often used with dependency injection. ```APIDOC ## Mapster Mapper Instance ### Description Illustrates the creation and usage of a `IMapper` instance for performing mappings, particularly useful in dependency injection scenarios. ### Methods - **`IMapper mapper = new Mapper()`**: Creates a new instance of the `Mapper`. - **`mapper.Map(src)`**: Maps a source object `src` to a new destination object of type `Dest` using the mapper instance. - **`mapper.Map(src, dest)`**: Maps a source object `src` to an existing destination object `dest` using the mapper instance. ### Links - [Mappers](xref:Mapster.Mapping.Mappers) ``` -------------------------------- ### Inline Configuration with Fork Source: https://github.com/mapstermapper/mapster/wiki/Home Apply a set of configurations inline using the `Fork` method. This allows for temporary or specific configuration overrides. ```csharp config.Fork(forked => ...) ``` -------------------------------- ### Basic Mapping with Adapt Extension Method Source: https://context7.com/mapstermapper/mapster/llms.txt Use the Adapt() extension method to create a new destination object from a source object. It automatically matches properties by name. You can also map to an existing object to merge values. Specify both types for value types to avoid boxing. ```csharp public class Person { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public Address Address { get; set; } } public class PersonDto { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public string AddressCity { get; set; } // Flattening: maps from Address.City } public class Address { public string City { get; set; } public string Street { get; set; } } ``` ```csharp // Simple mapping to new object var person = new Person { FirstName = "John", LastName = "Doe", Age = 30, Address = new Address { City = "New York", Street = "5th Avenue" } }; var dto = person.Adapt(); // dto.FirstName = "John" // dto.LastName = "Doe" // dto.Age = 30 // dto.AddressCity = "New York" (automatically flattened) ``` ```csharp // Mapping to existing object (merges values) var existingDto = new PersonDto { FirstName = "Jane" }; person.Adapt(existingDto); // existingDto now has all values from person ``` ```csharp // Avoid boxing with value types by specifying both types decimal price = 123.45m; var priceAsDouble = price.Adapt(); ``` -------------------------------- ### Map to Non-Public Setter Source: https://github.com/mapstermapper/mapster/wiki/Mapping-readonly-prop Mapster can automatically map to non-public setters. This example shows a class with a private setter for its Items collection. ```csharp public class Order { public string Id { get; set; } public ICollection Items { get; private set; } } ``` -------------------------------- ### Build Adapter with Parameters Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/mapping/Mappers.md Utilize the builder pattern to add runtime parameters during the mapping process, then adapt to the target type. ```csharp var dto = poco.BuildAdapter() .AddParameters("user", this.User.Identity.Name) .AdaptToType(); ``` -------------------------------- ### Global Mapster Configuration in Global.asax.cs Source: https://github.com/mapstermapper/mapster/wiki/Config-location Set up Mapster configurations once in your application's entry point, such as the Application_Start method in Global.asax.cs, to ensure they are available application-wide. ```csharp // Application_Start in Global.asax.cs config.ForType().Ignore("Id"); ``` -------------------------------- ### Instantiate IMapper Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/mapping/Mappers.md Create an instance of the IMapper interface for use in dependency injection or direct instantiation. ```csharp IMapper mapper = new Mapper(); ``` -------------------------------- ### Convention-Based Setup for Read-Only Collections Source: https://github.com/mapstermapper/mapster/wiki/Mapping-readonly-prop Apply the UseDestinationValue convention globally for all read-only ICollection<> types without annotating each one individually. ```csharp TypeAdapterConfig.GlobalSettings.Default .UseDestinationValue(member => member.SetterModifier == AccessModifier.None && member.Type.IsGenericType && member.Type.GetGenericTypeDefinition() == typeof(ICollection<>)); ``` -------------------------------- ### Ignore Properties on Generation Source: https://github.com/mapstermapper/mapster/wiki/Fluent-API-Code-generation Configure code generation to ignore properties based on attributes or lack thereof. This example ignores properties without a DataMemberAttribute. ```csharp config.AdaptTo("[name]Dto") .ForType() .IgnoreNoAttributes (typeof(DataMemberAttribute)); public class Student { [DataMember] public string Name { get; set; } //this property will be generated public string LastName { get; set; } //this will not be generated } ``` -------------------------------- ### Basic Usages Source: https://github.com/mapstermapper/mapster/wiki/Home Demonstrates fundamental mapping operations using Mapster's extension methods. ```APIDOC ## Basic Mapping Operations ### Description Provides methods for mapping objects to new types or existing objects, and projecting from queryable sources. ### Methods - `src.Adapt()`: Maps a source object to a new destination object of type `Dest`. - `src.Adapt(dest)`: Maps a source object to an existing destination object. - `query.ProjectToType()`: Maps a queryable source to a new destination type. ### Links - Basic Usages: [https://github.com/MapsterMapper/Mapster/wiki/Basic-usages](https://github.com/MapsterMapper/Mapster/wiki/Basic-usages) - Data Types: [https://github.com/MapsterMapper/Mapster/wiki/Data-types](https://github.com/MapsterMapper/Mapster/wiki/Data-types) ``` -------------------------------- ### Using IMapper Instance for Mapping Source: https://github.com/mapstermapper/mapster/wiki/Mappers Instantiate IMapper for dependency injection or when a mapper instance is needed. Use the Map method on the instance to perform mappings. ```csharp IMapper mapper = new Mapper(); ``` ```csharp var result = mapper.Map(source); ``` -------------------------------- ### Trim All Strings in Destination Objects Source: https://github.com/mapstermapper/mapster/wiki/Setting-values Employ `AddDestinationTransform` to apply a transformation to all properties of a specific type across destination objects. This example trims all string values. ```csharp TypeAdapterConfig.NewConfig() .AddDestinationTransform((string x) => x.Trim()); ``` -------------------------------- ### Define Parent and Child POCO Classes Source: https://github.com/mapstermapper/mapster/wiki/Config-for-nested-mapping Defines the structure for parent, child, and grandchild Plain Old C# Objects (POCOs) used in mapping examples. ```csharp class ParentPoco { public string Id { get; set; } public List Children { get; set; } public string Name { get; set; } } class ChildPoco { public string Id { get; set; } public List GrandChildren { get; set; } } class GrandChildPoco { public string Id { get; set; } } ``` -------------------------------- ### Define Mappings on a Config Instance Source: https://github.com/mapstermapper/mapster/wiki/Config-instance Use NewConfig or ForType on a specific config instance to define custom mappings. NewConfig replaces existing configurations, while ForType adds to or modifies existing ones. ```csharp config.NewConfig() .Map(dest => dest.FullName, src => string.Format("{0} {1}", src.FirstName, src.LastName)); ``` ```csharp config.ForType() .Map(dest => dest.FullName, src => string.Format("{0} {1}", src.FirstName, src.LastName)); ``` -------------------------------- ### Mapster Mapping in Controller Class Source: https://github.com/mapstermapper/mapster/wiki/Config-location Perform object mapping within controller classes using a pre-configured Mapster setup. Ensure the configuration object is accessible. ```csharp // in Controller class var dto1 = poco1.Adapt(config); var dto2 = poco2.Adapt(config); ``` -------------------------------- ### Map to Constructor with Custom Mapping Source: https://github.com/mapstermapper/mapster/wiki/Constructor-mapping When mapping to a constructor, use Pascal case for property names to match constructor parameters. Ensure the destination class has a constructor that accepts the mapped parameters. ```csharp TypeAdapterConfig.NewConfig() .MapToConstructor(true) .Map('Code', 'Id'); //use Pascal case ``` -------------------------------- ### Incorrect Configuration Reuse in Mapster Source: https://github.com/mapstermapper/mapster/wiki/Config-location Avoid reusing a compiled configuration for multiple mapping operations as it can lead to exceptions. Separate configuration setup from mapping execution. ```csharp config.ForType().Ignore("Id"); var dto1 = poco1.Adapt(config); config.ForType().Ignore("Id"); //<--- Exception occurred here, because config was already compiled var dto2 = poco2.Adapt(config); ``` -------------------------------- ### Clone Configuration Source: https://github.com/mapstermapper/mapster/wiki/Home Create a deep copy of an existing configuration instance. This is useful for creating variations of a configuration. ```csharp config.Clone() ``` -------------------------------- ### Get Specific Type Pair Settings Source: https://github.com/mapstermapper/mapster/wiki/Home Retrieves the configuration applied to a specific source and destination type pair. Useful for accessing or modifying existing specific mappings. ```csharp TypeAdapterConfig.ForType() config.ForType() ``` -------------------------------- ### Rule-Based Setting: Ignore 'Id' When Types Match Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/configuration/Configuration.md Use `When` in global settings to apply configurations conditionally. This example ignores the 'Id' property when the source and destination types are the same. ```csharp TypeAdapterConfig.GlobalSettings.When((srcType, destType, mapType) => srcType == destType) .Ignore("Id"); ``` -------------------------------- ### Config Scanning Source: https://github.com/mapstermapper/mapster/wiki/Home Details how to scan assemblies for configuration registrations and apply them. ```APIDOC ## Configuration Scanning ### Description Explains how to discover and apply mapping configurations from assemblies or directly from registered types. ### Interfaces and Methods - `IRegister`: Interface for custom configuration registration classes. - `config.Scan(...assemblies)`: Scans the specified assemblies for types implementing `IRegister` and applies their configurations. - `config.Apply(...registers)`: Applies configurations directly from provided `IRegister` instances. ### Links - Config Location: [https://github.com/MapsterMapper/Mapster/wiki/Config-location](https://github.com/MapsterMapper/Mapster/wiki/Config-location) ``` -------------------------------- ### Enable Two-Ways Mapping for Unflattening Source: https://github.com/mapstermapper/mapster/wiki/Two-ways Utilize the `TwoWays()` configuration to automatically handle unflattening for reverse mappings. This simplifies the setup when you need bidirectional mapping with nested properties. ```csharp TypeAdapterConfig .NewConfig() .TwoWays(); ``` -------------------------------- ### Pass Configuration to Mapper Instance Source: https://github.com/mapstermapper/mapster/wiki/Home Initialize a mapper instance with a specific configuration object. ```csharp new Mapper(config) ``` -------------------------------- ### Scan Inherited Types for Mapster Source: https://github.com/mapstermapper/mapster/wiki/Mapping-Configuration-With-IMapFrom-Interface Add this line to your startup configuration to enable Mapster to scan for mapping configurations in inherited types. This allows for more flexible mapping setups. ```csharp TypeAdapterConfig.GlobalSettings.ScanInheritedTypes(Assembly.GetExecutingAssembly()); ``` -------------------------------- ### Basic Adapt Extension Method Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/mapping/Mappers.md Use this extension method for simple mappings. It casts the source to object, which may cause boxing/unboxing for value types. ```csharp var dest = src.Adapt(); ``` -------------------------------- ### Adjust netstandard Assembly Path for Mac Source: https://github.com/mapstermapper/mapster/wiki/TextTemplate On macOS, if 'netstandard' is not found, you may need to provide a direct path to the 'netstandard.dll'. Adjust the path according to your .NET SDK installation. ```xml <#@ Assembly Name="netstandard" #> <#@ Assembly Name="/usr/local/share/dotnet/sdk/2.2.103/Microsoft/Microsoft.NET.Build.Extensions/net461/lib/netstandard.dll" #> ``` -------------------------------- ### Pass Configuration to Builder Source: https://github.com/mapstermapper/mapster/wiki/Home Initialize a mapping builder with a specific configuration object. ```csharp src.BuildAdapter(config) ``` -------------------------------- ### Apply Rule-Based Ignore Attribute for Projections Source: https://github.com/mapstermapper/mapster/wiki/Configuration Configure global settings to ignore specific attributes based on the map type. This example ignores the NotMapAttribute when the map type is a Projection. ```csharp TypeAdapterConfig.GlobalSettings.When((srcType, destType, mapType) => mapType == MapType.Projection) .IgnoreAttribute(typeof(NotMapAttribute)); ``` -------------------------------- ### Map Using IMapper Instance Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/mapping/Mappers.md Perform mapping using an existing IMapper instance by calling its Map method. ```csharp var result = mapper.Map(source); ``` -------------------------------- ### Rule-Based Naming using GetMemberName Source: https://github.com/mapstermapper/mapster/wiki/Naming-convention Define custom rules for determining member names during mapping using the GetMemberName method. This example uses the JsonProperty attribute to specify the destination member name. ```csharp TypeAdapterConfig.GlobalSettings.Default .GetMemberName(member => member.GetCustomAttributes(true) .OfType() .FirstOrDefault()?.PropertyName); //if return null, property will not be renamed ``` -------------------------------- ### Create Builder Instance Source: https://github.com/mapstermapper/mapster/wiki/Home Initiate a mapping builder. This is used for more complex mapping scenarios where inline configuration is needed. ```csharp src.BuildAdapter() ``` ```csharp mapper.From(src) ``` -------------------------------- ### Mapper Instance with Dependency Injection Source: https://context7.com/mapstermapper/mapster/llms.txt Use the IMapper interface and ServiceMapper class for dependency injection. Configure mappings with service injection by accessing services via MapContext.Current.GetService(). Register the TypeAdapterConfig and IMapper with your DI container. ```csharp // Install: dotnet add package Mapster.DependencyInjection // Startup configuration (Program.cs or Startup.cs) public void ConfigureServices(IServiceCollection services) { // Create and configure TypeAdapterConfig var config = new TypeAdapterConfig(); // Configure mapping with service injection config.NewConfig() .Map(dest => dest.FormattedDate, src => MapContext.Current.GetService().Format(src.OrderDate)) .Map(dest => dest.CustomerName, src => MapContext.Current.GetService().GetName(src.CustomerId)); // Register with DI container services.AddSingleton(config); services.AddScoped(); services.AddScoped(); services.AddScoped(); } ``` ```csharp // Service class using injected mapper public class OrderService { private readonly IMapper _mapper; private readonly IDbContext _db; public OrderService(IMapper mapper, IDbContext db) { _mapper = mapper; _db = db; } public OrderDto GetOrder(int id) { var order = _db.Orders.Find(id); return _mapper.Map(order); } public List GetAllOrders() { var orders = _db.Orders.ToList(); return _mapper.Map>(orders); } } ``` -------------------------------- ### Execute Custom Logic with Before/After Mapping Hooks Source: https://context7.com/mapstermapper/mapster/llms.txt Use AfterMapping for post-mapping tasks like validation or logging, and BeforeMapping for pre-mapping initialization. Supports interface-based hooks and provides a destination parameter for merge scenarios. ```csharp // After mapping - validation, logging, etc. TypeAdapterConfig .ForType() .AfterMapping((src, dest) => { dest.TotalWithTax = dest.Total * 1.1m; dest.MappedAt = DateTime.UtcNow; }); ``` ```csharp // Before mapping - initialization TypeAdapterConfig .ForType() .BeforeMapping((src, dest) => dest.Initialize()); ``` ```csharp // Interface-based after mapping for validation public interface IValidatable { void Validate(); } TypeAdapterConfig.GlobalSettings.ForDestinationType() .AfterMapping(dest => dest.Validate()); ``` ```csharp // With destination parameter for merge scenarios TypeAdapterConfig, IEnumerable>.NewConfig() .BeforeMapping((src, result, destination) => { if (destination != null && result is ICollection collection) { foreach (var item in destination) collection.Add(item); } }); var source = new List { 1, 2, 3 }; var destination = new List { 0 }; var result = source.Adapt(destination); // result = [0, 1, 2, 3] ``` ```csharp // For code generation, use inline versions TypeAdapterConfig .ForType() .AfterMappingInline(dest => Validator.Validate(dest)); ``` -------------------------------- ### Configure Destination Type with AfterMapping Source: https://github.com/mapstermapper/mapster/wiki/Configuration Use ForDestinationType to configure settings for a destination type without knowing the source type. This example sets up an AfterMapping hook to validate the destination object if it implements IValidator. ```csharp TypeAdapterConfig.GlobalSettings.ForDestinationType() .AfterMapping(dest => dest.Validate()); ``` -------------------------------- ### Clone an Existing Config Instance Source: https://github.com/mapstermapper/mapster/wiki/Config-instance Duplicate an existing configuration instance to create a new, independent configuration. This allows for modifications without affecting the original. ```csharp var newConfig = oldConfig.Clone(); ``` -------------------------------- ### Configure by Destination Type Source: https://github.com/mapstermapper/mapster/wiki/Home Retrieves settings that apply to a specific destination type, regardless of the source type. Useful for enforcing conventions on destination objects. ```csharp config.ForDestinationType() ``` -------------------------------- ### Mapster Code Generation Logic in T4 Template Source: https://github.com/mapstermapper/mapster/wiki/TextTemplate Define mapping configurations and generate C# code using Mapster's BuildAdapter and ToScript methods within a T4 template. This example generates a mapper for CustomerDTO. ```csharp <# //this line is to generate all nested mapping in 1 file TypeAdapterConfig.GlobalSettings.SelfContainedCodeGeneration = true; var cust = default(Customer); var def = new ExpressionDefinitions { IsStatic = true, //change to false if you want instance MethodName = "Map", Namespace = "YourNamespace", TypeName = "CustomerMapper" }; var code = cust.BuildAdapter() .CreateMapExpression() .ToScript(def); WriteLine(code); #> ``` -------------------------------- ### Copy All References to Output Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/tools/TextTemplate.md Configure your project to copy all referenced assemblies to the output directory, which can resolve 'library not found' errors when running T4 templates. ```xml true true ``` -------------------------------- ### Create a New Config Instance Source: https://github.com/mapstermapper/mapster/wiki/Config-instance Instantiate a new TypeAdapterConfig to manage settings independently from the global configuration. Use this to ignore specific properties like 'Id'. ```csharp var config = new TypeAdapterConfig(); config.Default.Ignore("Id"); ``` -------------------------------- ### Configure Per Type Pair with ForType Source: https://github.com/mapstermapper/mapster/wiki/Configuration Use ForType to configure mappings for a specific type pair. If a mapping exists, it enhances it; otherwise, it creates a new one. This is suitable when you want to incrementally build mapping configurations. ```csharp TypeAdapterConfig .ForType() .Ignore(dest => dest.Age) .Map(dest => dest.FullName, src => string.Format("{0} {1}", src.FirstName, src.LastName)); ``` -------------------------------- ### Custom Destination Object Creation with ConstructUsing Source: https://github.com/mapstermapper/mapster/wiki/Constructor-mapping Use `ConstructUsing` to provide a custom function for creating destination objects. This can be a constructor, factory method, or any function returning the expected type. ```csharp TypeAdapterConfig.NewConfig() .ConstructUsing(src => new TDestination(src.Id, src.Name)); ``` ```csharp TypeAdapterConfig.NewConfig() .ConstructUsing(src => new TDestination{Unmapped = "unmapped"}); ``` ```csharp TypeAdapterConfig.NewConfig() .ConstructUsing((src, destination) => new TDestination(src.Id, destination?.Name ?? src.Name)); ``` -------------------------------- ### Configure Type Mapping with ForType Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/configuration/Configuration.md Use `ForType` to configure mappings. If a mapping for the TSource => TDestination pair exists, it enhances the existing one; otherwise, it creates a new one. ```csharp TypeAdapterConfig .ForType() .Ignore(dest => dest.Age) .Map(dest => dest.FullName, src => string.Format("{0} {1}", src.FirstName, src.LastName)); ``` -------------------------------- ### Using Mapper Instance with EF Core for Projections Source: https://context7.com/mapstermapper/mapster/llms.txt Inject IMapper to perform projections within repository methods for cleaner EF Core query handling. The From() method initiates the mapping process on the queryable. ```csharp public class OrderRepository { private readonly IMapper _mapper; private readonly AppDbContext _context; public async Task> GetRecentOrdersAsync() { var query = _context.Orders.Where(o => o.Status == OrderStatus.Active); return await _mapper.From(query) .ProjectToType() .ToListAsync(); } } ``` -------------------------------- ### Create Mapper Instance Source: https://github.com/mapstermapper/mapster/wiki/Home Instantiate a new mapper object. This is useful for dependency injection scenarios. ```csharp IMapper mapper = new Mapper() ``` -------------------------------- ### Compile Projection Instructions Source: https://github.com/mapstermapper/mapster/wiki/Home Validate and cache mapping instructions specifically for queryable projections. This optimizes LINQ queries. ```csharp config.CompileProjection() ``` -------------------------------- ### Map Using a Mapper with a Specific Config Source: https://github.com/mapstermapper/mapster/wiki/Config-instance Create a Mapper instance with a specific configuration to perform mappings. This allows for encapsulated mapping logic. ```csharp var mapper = new Mapper(config); var result = mapper.Map(src); ``` -------------------------------- ### Fork Configuration for Specific Mappings Source: https://github.com/mapstermapper/mapster/wiki/Config-instance Use the Fork method to create a new configuration that inherits from an existing one but allows for specific, localized mappings. This is useful for maintaining configuration in one place while enabling variations. ```csharp var forked = mainConfig.Fork(config => config.ForType() .Map(dest => dest.code, src => src.Id)); var dto = poco.Adapt(forked); ``` -------------------------------- ### Using Injected Mapper Instance for Mapping Source: https://github.com/mapstermapper/mapster/wiki/Dependency-Injection Inject the IMapper instance into your services and use it to perform object mapping. ```csharp public class FooService { private readonly IMapper _mapper; public FooService(IMapper mapper) { _mapper = mapper; } public void DoSomething(Poco poco) { var dto = _mapper.Map(poco); ... } } ``` -------------------------------- ### Adapt Using a Specific Config Instance Source: https://github.com/mapstermapper/mapster/wiki/Config-instance Apply a custom configuration instance to the Adapt method to control the mapping process for a specific operation. Reusing config instances is recommended to avoid recompilation. ```csharp var result = src.Adapt(config); ``` -------------------------------- ### Configuration Options Source: https://github.com/mapstermapper/mapster/wiki/Home Details various configuration settings for customizing Mapster's behavior, including global settings, instance configurations, and validation. ```APIDOC ## Mapster Configuration ### Description Covers global and instance-specific configurations for customizing mapping behavior, validation, and inheritance. ### Configuration Access - `TypeAdapterConfig.GlobalSettings`: Accesses the global configuration settings. - `var config = new TypeAdapterConfig()`: Creates a new, isolated configuration instance. ### Applying Configurations - `src.Adapt(config)`: Applies a specific configuration to a mapping operation. - `new Mapper(config)`: Initializes a mapper instance with a specific configuration. - `src.BuildAdapter(config)`: Uses a specific configuration with the builder pattern. ### Validation Options - `config.RequireDestinationMemberSource`: Ensures all destination members have a corresponding source member. - `config.RequireExplicitMapping`: Requires explicit mapping definitions for all type pairs. ### Inheritance Options - `config.AllowImplicitDestinationInheritance`: Enables implicit mapping from base destination classes. - `config.AllowImplicitSourceInheritance`: Enables implicit mapping from base source classes. ### Code Generation - `config.SelfContainedCodeGeneration`: Generates all nested mappings within a single method. ### Compilation and Validation - `config.Compile()`: Validates mapping instructions and caches them for performance. - `config.CompileProjection()`: Validates and caches mapping instructions specifically for queryable projections. ### Configuration Cloning and Forking - `config.Clone()`: Creates a copy of the current configuration. - `config.Fork(forked => ...)`: Creates a new configuration by forking from an existing one, allowing inline modifications. ### Links - Configuration: [https://github.com/MapsterMapper/Mapster/wiki/Configuration](https://github.com/MapsterMapper/Mapster/wiki/Configuration) - Config Instance: [https://github.com/MapsterMapper/Mapster/wiki/Config-instance](https://github.com/MapsterMapper/Mapster/wiki/Config-instance) - Config Validation & Compilation: [https://github.com/MapsterMapper/Mapster/wiki/Config-validation-&-compilation](https://github.com/MapsterMapper/Mapster/wiki/Config-validation-&-compilation) - Config Inheritance: [https://github.com/MapsterMapper/Mapster/wiki/Config-inheritance](https://github.com/MapsterMapper/Mapster/wiki/Config-inheritance) - TextTemplate: [https://github.com/MapsterMapper/Mapster/wiki/TextTemplate](https://github.com/MapsterMapper/Mapster/wiki/TextTemplate) ``` -------------------------------- ### Mapping Multiple Sources - From a Tuple Source: https://github.com/mapstermapper/mapster/wiki/Custom-mapping Map properties from two different source objects to a single destination object by wrapping the sources in a tuple and mapping each item of the tuple. ```csharp TypeAdapterConfig<(Dto1, Dto2), Poco>.NewConfig() .Map(dest => dest, src => src.Item1) .Map(dest => dest, src => src.Item2); ``` -------------------------------- ### Generate Extension Methods with [GenerateMapper] Source: https://github.com/mapstermapper/mapster/wiki/Attribute-base-Code-generation Add the [GenerateMapper] attribute to a class annotated with [AdaptFrom], [AdaptTo], or [AdaptTwoWays] to automatically generate extension methods for mapping and projection. ```csharp [AdaptTo("[name]Dto"), GenerateMapper] public class Student { ... } ``` ```csharp public class StudentDto { ... } public static class StudentMapper { public static StudentDto AdaptToDto(this Student poco) { ... } public static StudentDto AdaptTo(this Student poco, StudentDto dto) { ... } public static Expression> ProjectToDto => ... } ``` -------------------------------- ### Configure Flexible Naming Conventions Source: https://context7.com/mapstermapper/mapster/llms.txt Configure Mapster to match property names flexibly, ignoring case, or applying custom name transformations. ```csharp // Flexible name matching (PascalCase, camelCase, snake_case, UPPER_CASE) TypeAdapterConfig.GlobalSettings.Default .NameMatchingStrategy(NameMatchingStrategy.Flexible); ``` ```csharp // Case-insensitive matching TypeAdapterConfig .NewConfig() .NameMatchingStrategy(NameMatchingStrategy.IgnoreCase); ``` ```csharp // Add prefix to source member names TypeAdapterConfig .NewConfig() .NameMatchingStrategy(NameMatchingStrategy.ConvertSourceMemberName(name => "m_" + name)); ``` ```csharp // Replace characters in names TypeAdapterConfig .NewConfig() .NameMatchingStrategy(NameMatchingStrategy.ConvertSourceMemberName( name => name.Replace("Ä", "A").Replace("Ö", "O"))); ``` ```csharp // Dictionary key casing TypeAdapterConfig> .NewConfig() .NameMatchingStrategy(NameMatchingStrategy.ToCamelCase); ``` ```csharp TypeAdapterConfig, Poco> .NewConfig() .NameMatchingStrategy(NameMatchingStrategy.FromCamelCase); ``` ```csharp // Rule-based naming with attributes TypeAdapterConfig.GlobalSettings.Default .GetMemberName(member => member.GetCustomAttributes(true) .OfType() .FirstOrDefault()?.PropertyName); ``` ```csharp // Usage example public class Source { [JsonProperty("user_id")] public string Id { get; set; } // Maps to "user_id" in destination } ``` -------------------------------- ### Direct Mapping with Adapt Extension Method Source: https://github.com/mapstermapper/mapster/wiki/Mappers Use the Adapt extension method for simple object-to-object mapping. For value types, prefer Adapt to avoid boxing. ```csharp var dest = src.Adapt(); ``` ```csharp var dest = src.Adapt(); ``` -------------------------------- ### Map Open Generic Types Source: https://github.com/mapstermapper/mapster/wiki/Configuration Configure mappings for open generic types by providing the generic type definitions to ForType. This allows setting up mappings for generic classes or interfaces. ```csharp TypeAdapterConfig.GlobalSettings.ForType(typeof(GenericPoco<>), typeof(GenericDto<>)) .Map("value", "Value"); ``` -------------------------------- ### Pass Configuration to Mapping Source: https://github.com/mapstermapper/mapster/wiki/Home Apply a specific configuration instance to a direct mapping operation. ```csharp src.Adapt(config) ``` -------------------------------- ### Inline Configuration with Builder Source: https://github.com/mapstermapper/mapster/wiki/Home Apply inline configuration to a mapping builder. This allows for specific mapping rules to be defined for a single operation. ```csharp .ForkConfig(config => ...) ``` -------------------------------- ### Use dotnet build with CopyLocalLockFileAssemblies flag Source: https://github.com/mapstermapper/mapster/wiki/Mapster.Tool Alternatively, you can pass the CopyLocalLockFileAssemblies flag directly to the dotnet build command. This is useful for build scripts or when modifying the csproj is not feasible. ```xml [...] ``` -------------------------------- ### Generate DTOs with Mapster.Tool Source: https://github.com/mapstermapper/mapster/wiki/Home Use the `dotnet mapster` command-line tool to generate Data Transfer Objects (DTOs) and mapping code during the build process. ```bash dotnet mapster ``` -------------------------------- ### Validate and Compile Mapster Mappings Source: https://context7.com/mapstermapper/mapster/llms.txt Ensure mapping configurations are correct by compiling them at startup. This helps catch errors early and optimizes runtime performance. ```csharp // Enable strict mapping modes TypeAdapterConfig.GlobalSettings.RequireExplicitMapping = true; // All types must be configured TypeAdapterConfig.GlobalSettings.RequireDestinationMemberSource = true; // All dest props need source ``` ```csharp // Register required mappings TypeAdapterConfig.NewConfig(); TypeAdapterConfig.NewConfig() .Map(dest => dest.Total, src => src.Items.Sum(i => i.Price)); ``` ```csharp // Compile and validate all at startup TypeAdapterConfig.GlobalSettings.Compile(); // Throws if invalid ``` ```csharp // Validate specific configuration var config = TypeAdapterConfig.NewConfig(); config.Compile(); ``` ```csharp // Instance compilation var config = new TypeAdapterConfig(); config.NewConfig(); config.NewConfig(); config.Compile(); // Validates all registrations ``` ```csharp // Recommended startup pattern public class Program { public static void Main(string[] args) { ConfigureMappings(); TypeAdapterConfig.GlobalSettings.Compile(); // Fail fast on startup // Application continues... } private static void ConfigureMappings() { TypeAdapterConfig.NewConfig() .Ignore(d => d.Password); // ... more configurations } } ``` -------------------------------- ### Configure Type Mapping with NewConfig Source: https://github.com/mapstermapper/mapster/blob/master/docs/articles/configuration/Configuration.md Use `NewConfig` to create a new mapping configuration for a specific type pair. This will drop any previous configuration for the same TSource => TDestination mapping. ```csharp TypeAdapterConfig .NewConfig() .Ignore(dest => dest.Age) .Map(dest => dest.FullName, src => string.Format("{0} {1}", src.FirstName, src.LastName)); ``` -------------------------------- ### Configure Per Type Pair Mapping Source: https://github.com/mapstermapper/mapster/wiki/Configuration Use NewConfig to create a new mapping configuration for a specific type pair, dropping any previous configuration. This is useful for defining unique mapping rules for a source-to-destination type combination. ```csharp TypeAdapterConfig .NewConfig() .Ignore(dest => dest.Age) .Map(dest => dest.FullName, src => string.Format("{0} {1}", src.FirstName, src.LastName)); ``` -------------------------------- ### Enable Json.Net Mapping Globally Source: https://github.com/mapstermapper/mapster/wiki/Json.net Call `EnableJsonMapping` on `TypeAdapterConfig.GlobalSettings` to enable Json.Net mapping for all configurations. ```csharp TypeAdapterConfig.GlobalSettings.EnableJsonMapping(); ``` -------------------------------- ### Compile Mapping Instructions Source: https://github.com/mapstermapper/mapster/wiki/Home Validate all mapping instructions and cache them for improved performance. This should be called after all configurations are set. ```csharp config.Compile() ```