简体   繁体   中英

Not able to connect to an external database ASP.NET

I'm trying to connect to an external database with my ASP.NET API but I keep getting this error:

Microsoft.Data.SqlClient.SqlException: 'Invalid object name 'Parkings'.' An exception of type 'Microsoft.Data.SqlClient.SqlException' occurred in Microsoft.EntityFrameworkCore.Relational.dll but was not handled in user code Invalid object name 'Parkings'.

However, I am able to connect to the database from my nodejs server applications where I seed the database with data.

Code:

IP, username and password not shown for obvious reasons

appsettings.json :

{
  "ConnectionStrings": {
    "ParkingContext": "Server=xxx.xxx.xxx.xxx,xxxxx;Database=Parkings;User Id=xxxxx;Password=xxxxxx;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Startup.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();

        });
    }
}

Context class

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);
    }
}

First of all, I don't think you should be specifying the connection string twice. You are specifying it here:

services.AddDbContext<ParkingContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("ParkingContext")));

And here:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
        var connectionString = @"Server=xxx.xxx.xxx.xxx,xxxx;Database=Parkings;User Id=xxxx;Password=xxxx;";
        optionsBuilder.UseSqlServer(connectionString);
    }

The first one is sufficient.

EntityFrameWork is an ORM, so you need to make sure that your DbSets corresponds to existing tables in the database and all properties in your entities corresponds to existing columns in those tables.

If you check all this and it still fails. Then Read this post from MSDN code first to an existing database

You could try using the InitialCatalog property in the connection string, instead of the Database property. Otherwise make sure the "Parkings" object is correctly used here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM