0

I created a web api using .net core 3.1 database first. After running the

Scaffold-DbContext "Server=192.168.100.100;Database=CHEID;User Id=sa; Password=mypassword;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

it gave me a a DBcontext called "CHEIDContext". I was informed that I need to put the connection string in the appsettings.json so that's what I did.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
    "ConnectionStrings": {
      "DefaultConnectionString": "Server=192.168.100.100;Database=CHEID;User Id=sa; Password=mypassword;"
    },
  "AllowedHosts": "*"
}

This is my CHEIDContext.cs

public partial class CHEIDContext : DbContext
    {
        public CHEIDContext()
        {
        }

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

        public virtual DbSet<EntryImages> EntryImages { get; set; }
        public virtual DbSet<EntryInfo> EntryInfo { get; set; }
        public virtual DbSet<StagingDataCash> StagingDataCash { get; set; }
        public virtual DbSet<StagingDataEtc> StagingDataEtc { get; set; }
        public virtual DbSet<StagingDataImage> StagingDataImage { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                IConfigurationRoot configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json")
                    .Build();
                var connectionString = configuration.GetConnectionString("ConnectionStrings");
                optionsBuilder.UseSqlServer(connectionString);
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<EntryImages>(entity =>
            {
                entity.HasKey(e => new { e.PlazaAutoId, e.PlazaCode })
                    .HasName("PK_TestImage");

                entity.Property(e => e.UploadDtime)
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("(getdate())");
            });

            modelBuilder.Entity<EntryInfo>(entity =>
            {
                entity.HasKey(e => new { e.PlazaAutoId, e.PlazaCode });

                entity.Property(e => e.Action)
                    .HasMaxLength(1)
                    .IsUnicode(false);

                entity.Property(e => e.Id).ValueGeneratedOnAdd();

                entity.Property(e => e.PlateNumber)
                    .HasMaxLength(10)
                    .IsUnicode(false);

                entity.Property(e => e.TrxnDtime).HasColumnType("datetime");

                entity.Property(e => e.UploadDtime)
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("(getdate())");
            });

            modelBuilder.Entity<StagingDataCash>(entity =>
            {
                entity.Property(e => e.DetectionDateTime).HasColumnType("datetime");

                entity.Property(e => e.Epc)
                    .HasMaxLength(100)
                    .IsUnicode(false);

                entity.Property(e => e.ImageFileName)
                    .HasMaxLength(250)
                    .IsUnicode(false);

                entity.Property(e => e.ImgUploadDtime).HasColumnType("datetime");

                entity.Property(e => e.PlateNumber)
                    .HasMaxLength(10)
                    .IsUnicode(false);

                entity.Property(e => e.PostingDtime)
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("(getdate())");

                entity.Property(e => e.TagNumber)
                    .HasMaxLength(10)
                    .IsUnicode(false);

                entity.Property(e => e.Tid)
                    .HasMaxLength(100)
                    .IsUnicode(false);

                entity.Property(e => e.TxtFileName)
                    .HasMaxLength(250)
                    .IsUnicode(false);

                entity.Property(e => e.UploadDtime).HasColumnType("datetime");
            });

            modelBuilder.Entity<StagingDataEtc>(entity =>
            {
                entity.Property(e => e.DetectionDateTime).HasColumnType("datetime");

                entity.Property(e => e.Epc)
                    .HasMaxLength(100)
                    .IsUnicode(false);

                entity.Property(e => e.ImageFileName)
                    .HasMaxLength(250)
                    .IsUnicode(false);

                entity.Property(e => e.ImgUploadDtime).HasColumnType("datetime");

                entity.Property(e => e.PlateNumber)
                    .HasMaxLength(10)
                    .IsUnicode(false);

                entity.Property(e => e.PostingDtime)
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("(getdate())");

                entity.Property(e => e.TagNumber)
                    .HasMaxLength(10)
                    .IsUnicode(false);

                entity.Property(e => e.Tid)
                    .HasMaxLength(100)
                    .IsUnicode(false);

                entity.Property(e => e.TxtFileName)
                    .HasMaxLength(250)
                    .IsUnicode(false);
            });

            modelBuilder.Entity<StagingDataImage>(entity =>
            {
                entity.HasKey(e => new { e.PlazaAutoId, e.PlazaCode, e.ImgSource });

                entity.Property(e => e.PostingDtime)
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("(getdate())");

                entity.Property(e => e.UploaDtime).HasColumnType("datetime");
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

This is my startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
           
            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

When I try to create a Controller using "MVC Controller with views, using Entity Framework" and I use the Data context class CHEIDContext, I get this error:

There was an error running the selected code generator: 'Value cannot be null, [Parameter:'connectionString']
2
  • Are your config wired up correctly for other things? Show your startup bindings (where you do DI setup, configure, configureservices etc) where you said addDbContext/useSqlServer etc Commented Mar 5, 2021 at 9:16
  • @CaiusJard Please see my edit Sir Commented Mar 5, 2021 at 9:20

1 Answer 1

2

Instead of

var connectionString = configuration.GetConnectionString("ConnectionStrings");

Use

var connectionString = configuration.GetConnectionString("DefaultConnectionString");

In appsettings.json file:

"ConnectionStrings": {
      "DefaultConnectionString": "Data Source=192.168.100.100;Initial Catalog=CHEID;User ID=sa; Password=mypassword;"
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.