[英]Not able to connect to an external database ASP.NET
我正在尝试使用我的 ASP.NET API 连接到外部数据库,但我不断收到此错误:
Microsoft.Data.SqlClient.SqlException: '无效的对象名称'停车场'。 Microsoft.EntityFrameworkCore.Relational.dll 中出现类型为“Microsoft.Data.SqlClient.SqlException”的异常,但未在用户代码中处理 无效的对象名称“Parkings”。
但是,我能够从我的 nodejs 服务器应用程序连接到数据库,在那里我为数据库设置了数据。
代码:
出于显而易见的原因未显示 IP、用户名和密码
appsettings.json
:
{
"ConnectionStrings": {
"ParkingContext": "Server=xxx.xxx.xxx.xxx,xxxxx;Database=Parkings;User Id=xxxxx;Password=xxxxxx;"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
启动.cs:
public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services) {
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddDbContext<ParkingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ParkingContext")));
services.AddScoped<IParkingRepository, ParkingRepository>();
services.AddSwaggerDocument();
services.AddCors(options => options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin()));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
} else {
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseSwaggerUi3();
app.UseSwagger();
app.UseRouting();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
}
}
public class ParkingContext : DbContext {
public DbSet<Parking> Parkings { get; set; }
public DbSet<Entry> Entries { get; set; }
public ParkingContext(DbContextOptions<ParkingContext> options) : base(options) {
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
var connectionString = @"Server=xxx.xxx.xxx.xxx,xxxx;Database=Parkings;User Id=xxxx;Password=xxxx;";
optionsBuilder.UseSqlServer(connectionString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
}
}
首先,我认为您不应该两次指定连接字符串。 您在此处指定它:
services.AddDbContext<ParkingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ParkingContext")));
和这里:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
var connectionString = @"Server=xxx.xxx.xxx.xxx,xxxx;Database=Parkings;User Id=xxxx;Password=xxxx;";
optionsBuilder.UseSqlServer(connectionString);
}
第一个就够了。
EntityFrameWork 是一个 ORM,因此您需要确保您的 DbSets 对应于数据库中的现有表,并且实体中的所有属性对应于这些表中的现有列。
您可以尝试在连接字符串中使用InitialCatalog
属性,而不是Database
属性。 否则,请确保此处正确使用“停车”对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.