-
Notifications
You must be signed in to change notification settings - Fork 22
Home
Leonardo Porro edited this page Feb 8, 2023
·
52 revisions
dotnet add package Detached.Mappers.EntityFramework
Or use an existing one, no changes to the DbContext class are needed.
public class TestDbContext : DbContext
{
public DbSet<User> Users { get; set; }
}
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();
});
}
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();
}
}
- Check getting started on dotnetfiddle.net
- Mapping graphs