Reputation: 171
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.
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
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
"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. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Upvotes: 0
Views: 146
Reputation: 171
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
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;");
}
}
Upvotes: 1