Search code examples
c#.net-6.0razor-pagesazure-data-studio

.NET 6 not recognizing database from Azure Data Studio


I am trying to connect to a database for my application in .NET 6. My connection string is as follows:

"ConnectionStrings": {
        "Default": "Server=localhost;Database=Tim;User Id=SA;Password=*****;TrustServerCertificate=true"
}

It is defined in appsettings.json.

In Azure Data Studio, I have a database named Tim which I am trying to access:

enter image description here

But when I run my application I get the following error

SqlException: Invalid object name 'Tim'.
Microsoft.Data.SqlClient.SqlCommand+<>c.b__209_0(Task result) System.Threading.Tasks.ContinuationResultTaskFromResultTask<TAntecedentResult, TResult>.InnerInvoke()
System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, object state)
System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, object state)
System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref Task currentTaskSlot, Thread threadPoolThread)
Dapper.SqlMapper.QueryAsync(IDbConnection cnn, Type effectiveType, CommandDefinition command) in SqlMapper.Async.cs
DataLibrary.DB.SqlDb.LoadData<T, U>(string storedProcedure, U parameters, string connectionStringName)
RPDemoApp.Pages.Orders.CreateModel.OnGet() in Create.cshtml.cs

  • var food = await _foodData.GetFood();
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory+NonGenericTaskHandlerMethod.Execute(object receiver, object[] arguments)
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeHandlerMethodAsync()
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeNextPageFilterAsync()
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync()
    Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

What mistake am I making?

EDIT: here is my Service collector code

builder.Services.AddSingleton(new ConnectionStringData
{
    SqlConnectionName= "DefaultConnection"
});

builder.Services.AddSingleton<IDataAccess, SqlDb>();
builder.Services.AddSingleton<IFoodData, FoodData>();
builder.Services.AddSingleton<IOrderData, OrderData>();

Here is the GetFood method, it uses a stored procedure to get data from the database:

public Task<List<FoodModel>> GetFood()
{
    return _dataAccess.LoadData<FoodModel, dynamic>("dbo.spFood_All",
                                                            new { },
                                                            _connectionString.SqlConnectionName);
}

Solution

  • In your settings file change Connection to DefaultConnection, Source to Data Source and Database to Initial Catalog as follows:

    "ConnectionStrings": {
        "DefaultConnection": "Data Source=localhost;Initial Catalog=Tim;User Id=sa;Password=Password;TrustServerCertificate=true;"
      },
    

    UPDATE:

    The error is 100% related to the stored procedure code. The select is referencing a database instead of a table.

    Please change the stored procedure select statement to use the table name.

    You can also use [DBNAME].[SCHEMA].[TABLENAME] so something like:

    CREATE PROCEDURE [dbo].[spFood_All] 
    AS 
    BEGIN
        SET NOCOUNT ON;
    
        SELECT
            [ID], [Title], [Descrip], [Price] 
        FROM
            Tim.dbo.[TABLENAME]; 
    END