简体   繁体   中英

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.

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)

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

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