是否可以将 asp.net 核心 2.1 Web API 与 SQL Server 中的现有数据库连接?



我看到Visual Studio的官方视频展示了如何做到这一点。但最终,教师无法使其工作,他必须在 Startup.cs 中使用 UseInMemoryDatabase(( 更改 UseSqlServer((。

这是我的代码,我遵循他的指示。 首先,创建一个包含类的文件,其中一个包含 Dbcontext,其他类与数据库中的表映射。就我而言,数据库只有一个表:学生。这是包含 Dbcontext 的类:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HoangHoaTham.WebAPI.Entities
{
public class TodoContext : DbContext
{
public TodoContext(DbContextOptions<TodoContext> options) : base(options)
{
}
public DbSet<Students> Students;
}
}

我的Startup.cs,我在这里添加UseSqlServer:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HoangHoaTham.WebAPI.Entities;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace HoangHoaTham
{
public class Startup
{   
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TodoContext>(options
=> options.UseSqlServer(Configuration.GetConnectionString("HoangHoaTham")));

services.AddMvc();
}
//You don't need to reed the code below
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}

最后,我将 ConnectionString 添加到 appsetting.json 中:

{
"ConnectionString": {
"HoangHoaTham": "Server=PC-PC\SQLEXPRESS;Database=HoangHoaThamHighSchool;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}

呃,它不起作用。错误 :

在此处输入图像描述

这是他的视频: https://www.youtube.com/watch?v=aIkpVzqLuhA 跳到50:47,看看他是怎么做到的。 非常感谢。

错误告诉您Configuration.GetConnectionString("HoangHoaTham")的结果是null。因此,您的配置存在一些问题,事实证明存在:appsettings.json 中的连接字符串部分应该是ConnectionStrings(复数(。相反,你有ConnectionString(单数(。

错误是针对您使用ConnectionStringappsetting.json只需根据您的要求在appsetting.json1 and tweak the连接字符串中尝试此代码即可。

ASP.NET 核心网页接口

{
"ApplicationInsights":{
"InstrumentationKey":""
},
"ConnectionStrings":{
"DefaultConnection":"Server=srvrName;Database=Test;User Id=User;Password=pass"
},
"Logging":{
"LogLevel":{
"Default":"Warning"
}
},
"AllowedHosts":"*"
}

相关内容

最新更新