Skip to content
Leonardo Porro edited this page Feb 8, 2023 · 52 revisions

Install Nu-Get package

dotnet add package Detached.Mappers.EntityFramework

Create your regular DbContext

Or use an existing one, no changes to the DbContext class are needed.

public class TestDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
}

Register and Configure

The library requires the registration of some internal services in the DbContext. On ASP.NET, this is usually configured in the DI container at the beggining (Startup.cs).

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MainDbContext>(cfg =>
    {
        ...
        cfg.UseMapping();
    });
} 

Start mapping!

using Detached.Mappers.EntityFramework

public class MyService
{
   readonly TestDbContext _dbContext;

   public MyService(TestDbContext dbContext)
   {
       _dbContext = dbContext;
   }

   public async Task Execute()
   {
       User user1 = await _dbContext.MapAsync<User>(new UserDTO { Id = 1, Name = "newUser" } );

       User user2 = await _dbContext.MapAsync<User>(new User { Id = 1, Name = "this User was mapped from an Entity" });
		
       User user3 = await _dbContext.MapAsync<User>(new UserDTO { Id = 2, Name = "this User was mapped from a DTO" });
		
       User user4 = await _dbContext.MapAsync<User>(new { Id = 3, Name = "this User was mapped from an Anonymous Type" });
		
       User user5 = await _dbContext.MapAsync<User>(new Dictionary<string, object> { { "Id", 4 }, { "Name", "this User was mapped from a Dictionary" });

       await _dbContext.SaveChangesAsync();
   }
}

See next