使用实体框架的数据库第一个错误

时间:2021-03-05 09:13:21

标签: c# entity-framework

我首先使用 .net core 3.1 数据库创建了一个 web api。运行后

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

它给了我一个名为“CHEIDContext”的 DBcontext。我被告知我需要将连接字符串放在 appsettings.json 中,这就是我所做的。

{
  "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": "*"
}

这是我的 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);
    }
}

这是我的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?}");
            });
        }
    }

当我尝试使用“带有视图的 MVC 控制器,使用实体框架”创建控制器并使用数据上下文类 CHEIDContext 时,出现此错误:

There was an error running the selected code generator: 'Value cannot be null, [Parameter:'connectionString']

1 个答案:

答案 0 :(得分:2)

代替

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

使用

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

在 appsettings.json 文件中:

"ConnectionStrings": {
      "DefaultConnectionString": "Data Source=192.168.100.100;Initial Catalog=CHEID;User ID=sa; Password=mypassword;"
    }