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