Skip to content

Entity Framework

Leonardo Porro edited this page Dec 10, 2024 · 7 revisions

As mentioned in other articles of the wiki, this library was made to work with or without EntityFramework, and to be extended to other ORMs if needed. To achieve this, it is splitted in different nuget packages:

  • Detached.Annotations: Contains annotation attributes for configuration, without any other reference. Ready to be added to a Model layer without polluting it with EF or other unneeded libraries.

  • Detached.Mappers: Core library with all of the mapping logic.

  • Detached.Mappers.EntityFramework: Base Mapper adapted to work with EF Core 6.0+

EF part of the library uses IDbContextOptionsExtensions to configure the DbContext internal services and add the mapper required services.

Configuration

Adding library mapper to DbContext services allows using Map/MapAsync extension methods to perform mapping operations.

Using AddDbContext
services.AddDbContext<MainDbContext>(cfg =>
{
   cfg.UseMapping(mapperOptions => {
      
      mapperOptions.Default(profileOptions => {

      });
      ...
   });
});
Using OnConfiguring
public class MyDbContext : DbContext
{
   protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
   {
       optionsBuilder.UseMapping(mapperOptions => {
      
          mapperOptions.Default(profileOptions => {
             ...
          });
        });
   }
}

See next