0

I'm trying to create a project in WebAPI using 3-Tier architecture and I want to add a database using the EntityFramework code first. As I understand, I need to add my datacontext into WebAPi project, Startup.cs since I always get the exception that DbContext is not configured.

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<DatabaseContext>();
        }

And seems like it ruins the architecture because I need to add using DataAccess to connect my DbContext. Am I right and if so, how to connect my DBContext properly?

DatabaseContext.cs

namespace Data.Context
{
    public class DatabaseContext : DbContext
    {
        public class OptionsBuild
        {
            public OptionsBuild()
            {
                settings = new AppConfiguration();
                optionsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
                optionsBuilder.UseSqlServer(settings.SqlConnectionString);
                databaseOptions = optionsBuilder.Options;
            }
            public DbContextOptionsBuilder<DatabaseContext> optionsBuilder { get; set; }
            public DbContextOptions<DatabaseContext> databaseOptions { get; set; }
            private AppConfiguration settings { get; set; }
        }

        public static OptionsBuild options = new OptionsBuild();

        public DatabaseContext() { }
        public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { }

        public DbSet<UserEntity> UserEntities { get; set; }
        public DbSet<RoleEntity> RoleEntities { get; set; }
        public DbSet<TestEntity> TestEntities { get; set; }
    }
}

I guess that I provided not enough code for you to answer. If so, please tell me what to add because I don't really know what is going to be helpful. Thanks in advance!

  • What is the practical problem caused by registering a DbContext in your web layer? Answer: there isn't one, unless you slavishly try to follow architectural guidelines without applying common sense and pragmatism. – Ian Kemp Nov 08 '20 at 19:54
  • Have you taken a look at this? https://stackoverflow.com/questions/43463114/referencing-dbcontext-in-startup-cs-is-messing-up-my-architecture-in-net-core-a – Martin Ferrari Nov 08 '20 at 20:01
  • Does this answer your question? [Referencing DbContext in StartUp.cs is messing up my architecture in .NET Core app](https://stackoverflow.com/questions/43463114/referencing-dbcontext-in-startup-cs-is-messing-up-my-architecture-in-net-core-a) – Martin Ferrari Nov 08 '20 at 20:03
  • @IanKemp Thanks for your reply! The problem is that it's my project in the university and I was asked to use 3 Layer architecture. That's why I try hard to follow all of the rules of the architecture. Anyway, as I understand, It's okay if WEB API uses both DAL and BLL and it doesn't ruin the architecture? – bidlocoder228 Nov 10 '20 at 16:55

0 Answers0