【发布时间】:2018-05-31 08:28:08
【问题描述】:
每当我使用 localdb 运行 asp.net 解决方案时,我都会遇到一个令人沮丧的问题。我总是遇到这个异常。
我的问题是,我该如何解决这个问题?我只是希望它生成一个小型本地数据库,我可以在其中通过 REST API 执行 CRUD 操作
System.Data.SqlClient.SqlException: '建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。 (提供者:SQL 网络接口,错误:50 - 发生本地数据库运行时错误。无法创建自动实例。有关错误详细信息,请参阅 Windows 应用程序事件日志。
DbInitializer.cs
using NMBSAPICore.Models;
using System;
using System.Linq;
namespace NMBSAPICore.Data
{
public class DbInitializer
{
public static void Initialize(NMBSAPICoreContext context)
{
if (context.Station.Any())
{
return; // DB has been seeded
}
var stations = new Station[] {
new Station { Naam = "Olen", Sporen = 2 }
};
foreach (Station s in stations)
{
context.Station.Add(s);
}
context.SaveChanges();
}
}
}
Startup.cs 配置
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<NMBSAPICoreContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("NMBSAPICoreContext")));
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = " NMBS API", Version = "v1" });
});
}public void Configure(IApplicationBuilder app, IHostingEnvironment env , NMBSAPICoreContext NMBSAPIContext)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
DbInitializer.Initialize(NMBSAPIContext);
}
}
上下文文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Protocols;
namespace NMBSAPICore.Models
{
public class NMBSAPICoreContext : DbContext
{
public NMBSAPICoreContext(DbContextOptions<NMBSAPICoreContext>options):
base(options)
{
}
public DbSet<Station> Station { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Station>().ToTable("Stations");
}
}
}
连接字符串:
"ConnectionStrings": {
"NMBSAPICoreContext": "Server=(localdb)\\mssqllocaldb;Database=NMBSDb;Trusted_Connection=True;MultipleActiveResultSets=true"
}
sqllocaldb 信息
.\IIS_DB
aspnetIceOnWheels
aspnet-IceOnWheels-1
localdb
mssqllocald
MSSQLLocalDB
NMBSAPICore
ProjectsV13
v11.0
我不想发布太多代码,因为它与我的问题无关,因为它也发生在新项目中,并尝试使用 localDb 运行。
如您所见,我使用 Swagger api,因此无法轻松测试我的 API 调用。我有多台计算机,但没有一台计算机进行 localdb 生成工作。
这是否意味着我在所有设备上都错误地安装了 SQL Server Express?微软声明我应该默认在/users/name/中生成一个mdf文件,我的什么都不做。
我已经安装了 SMSS 和 SQL Server Express 2017。
【问题讨论】:
-
请出示您的连接字符串
-
有添加,抱歉忘记了
-
请打开 cmd 窗口并输入:sqllocaldb info。结果如何?
-
我把它放在我的主要问题中,评论中的代码标记在做奇怪的事情
标签: c# asp.net sql-server asp.net-mvc