Friday, June 14, 2019

Set up the database-first approach to Entity Framework in a .NET Core application?

This isn't my code. It is a coworker's. I cannot guarantee that I'm not missing something. Into this Startup.cs let's loop in AutoMapper at the last line of the ConfigureServices method like so:

services.AddAutoMapper(typeof(Startup));

 
 

Next we are going to add the following two lines just inside of the ConfigureIoC method:

var connect = Configuration["MyConnectionString"];
services.AddDbContextPool<MyDbContext>(options => options.UseSqlServer(connect));

 
 

What is MyDbContext? Let's define that.

using Microsoft.EntityFrameworkCore;
using Trifecta.Infrastructure.Entities;
namespace Trifecta.Infrastructure.DBContext
{
   public class MyDbContext : DbContext
   {
      public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }
      
      public virtual DbSet<BusinessUnit> BusinessUnits { get; set; }
      public virtual DbSet<FileUpload> FileUploads { get; set; }
      
      protected override void OnModelCreating(ModelBuilder modelBuilder)
      {
         modelBuilder.Entity<BusinessUnit>().ToTable("BusinessUnit");
         modelBuilder.Entity<FileUpload>().ToTable("FileUpload", "Other");
      }
   }
}

 
 

"Other" above shows off how to access a schema other than dbo. Use this stuff in a repository like so:

namespace Trifecta.Infrastructure.ExternalDependencies.Repositories
{
   public class BusinessUnitRepository : IBusinessUnitRepository
   {
      protected DbContext Context { get; private set; }
      protected IMapper _mapper { get; private set; }
      private DbSet<BusinessUnit> DbSetBusinessUnit{ get; set; }
      
      public BusinessUnitRepository(IMapper mapper, MyDbContext dbContext)
      {
         this.Context = dbContext;
         this._mapper = mapper;
      
         this.DbSetBusinessUnit = this.Context.Set<BusinessUnit>();
      }
      
      public async Task<IEnumerable<IBusinessUnit>> GetBusinessUnits(params object[]
            parameters)
      {
         var entity = await this.DbSetBusinessUnit.ToListAsync();
      
         return _mapper.Map<List<BusinessUnit>, List<IBusinessUnit>>(entity);
      }

 
 

How does something which takes IMapper at its signature find the AutoMapper.Profile for a map? It seems like magic to me? Maybe some service locator wackiness is going on within the AutoMapper library.

No comments:

Post a Comment