ASP.NET Core 6.0执行Update-Database时遇连接字符串未初始化错误
ASP.NET Core 6.0 API Update-Database 错误与警告修复
一、"The ConnectionString property has not been initialized." 错误修复
错误原因
- 连接字符串拼写错误:appsettings.json中
Intregrated Security拼写错误,正确应为Integrated Security - DbContext未正确绑定连接字符串:数据库上下文类未配置读取appsettings中的连接字符串,导致EF Core无法建立数据库连接
解决步骤
修正appsettings.json拼写错误
将连接字符串中的Intregrated Security改为Integrated Security,修正后的代码片段:{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "sqlConnection": "(localdb)\\MSSQLLocalDB; Initial Catalog = bsStoreApp; Integrated Security=true;" } }配置DbContext与连接字符串绑定
首先创建数据库上下文类(示例命名为AppDbContext):using Microsoft.EntityFrameworkCore; using WebApi.Models; namespace WebApi.Data { public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Book> Books { get; set; } } }然后在
Program.cs中注册DbContext并读取连接字符串:var builder = WebApplication.CreateBuilder(args); // 注册DbContext,绑定连接字符串 builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("sqlConnection"))); // 其他服务配置... var app = builder.Build(); // 中间件配置... app.Run();
二、Decimal类型警告修复
警告原因
EF Core检测到Book类的Price属性未在模型层显式指定decimal的精度和刻度,尽管迁移文件中已设置decimal(18,2),但模型定义与数据库配置未对齐,触发警告以避免潜在的数据截断风险。
解决方法(二选一即可)
使用数据注解配置
在Book.cs的Price属性上添加[Column]注解:using System.ComponentModel.DataAnnotations.Schema; namespace WebApi.Models { public class Book { public int Id { get; set; } public string Title { get; set; } [Column(TypeName = "decimal(18,2)")] public decimal Price { get; set; } } }使用Fluent API配置
在AppDbContext的OnModelCreating方法中配置属性:protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Book>() .Property(b => b.Price) .HasPrecision(18, 2); // 或使用HasColumnType("decimal(18,2)") }
内容的提问来源于stack exchange,提问作者nurinn
相关产品推荐
相关产品推荐

