[英]Getting SQL Server error when adding data to database using ASP.NET Web API
I am trying to add some data to a ASP.NET Web API from the same solution, but somehow I am getting this error from SQL Server.我试图从同一解决方案向 ASP.NET Web API 添加一些数据,但不知何故我从 SQL Server 收到此错误。
This is my context这是我的上下文
public class SampleCtxt: DbContext
{
public DbSet<TodoItem> TodoItems { get; set; }
public SampleCtxt(DbContextOptions<SampleCtxt> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=.\SQLEXPRESS;Database=APITESTDB; Initial Catalog=APITestDb; Trusted_Connection=True;");
}
}
Configure services method from API从 API 配置服务方法
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<SampleCtxt>(opt =>
Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False; Database = APITESTDB;"));
opt.UseSqlServer(
Configuration
.GetConnectionString("DefaultConnection")));
services.AddControllers();
}
Connection string from json来自 json 的连接字符串
"ConnectionStrings": {
"DefaultConnection": "Server=.\\SQLEXPRESS;Database=APITESTDB; Initial Catalog=APITestDb Trusted_Connection=True;"
},
Adding data from another console project从另一个控制台项目添加数据
static void Main(string[] args)
{
using (SampleCtxt ctxt = new SampleCtxt(
new Microsoft.EntityFrameworkCore.DbContextOptionsBuilder<SampleCtxt>().Options))
{
TodoItem todoItem = new TodoItem() { Name = "qualquer" };
ctxt.TodoItems.Add(todoItem);
ctxt.SaveChanges();
}
}
Everything seems fine but I am getting this error:一切似乎都很好,但我收到此错误:
Verify that the instance name is correct and that SQL Server is configured to allow remote connections.验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。 (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) (提供者:SQL 网络接口,错误:26 - 错误定位服务器/指定的实例)
Its seens that the ConnectionString was wrong and the instantiation of the class context, I solved the problem by adding a parameterless constructor and by correcting the OnConfiguring Method它看到 ConnectionString 是错误的,并且类上下文的实例化,我通过添加一个无参数构造函数并通过更正 OnConfiguring 方法解决了这个问题
public class SampleCtxt: DbContext
{
public DbSet<TodoItem> TodoItems { get; set; }
public SampleCtxt()
{
}
public SampleCtxt(DbContextOptions<SampleCtxt> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=APITESTDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.