I am trying to connect my ASP.NET Core 6 application to SQL Server, but I get an error on the connection string. Does anyone have experience with .NET 6 that could help?
This is my code in my class ( book.cs
). I get the ERROR where I commented in the code. And yes I have the right string in the app.json
file
public class Book
{
public int BookId { get; set; }
public int Pagecount { get; set; }
public string Title { get; set; }
public string TypeName { get; set; }
public string AutherFirstName { get; set; }
public string AutherLastName { get; set; }
public List<Book> GetBooks(string connectionString)
{
List<Book> bookList = new List<Book>();
SqlConnection con = new SqlConnection (connectionString);
string selectSQL = "select BookId, Title, Isbn, PublisherName, AuthorName, CategoryName from GetBookData";
con.Open(); // Here i get my error
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr != null)
{
while (dr.Read())
{
Book book = new Book();
book.BookId = Convert.ToInt32(dr["BookId"]);
book.Pagecount = Convert.ToInt32(dr["pagecount"]);
book.Title = dr["Title"].ToString();
book.TypeName = dr["TypeName"].ToString();
book.AutherLastName = dr["AutherLastName"].ToString();
book.AutherFirstName = dr["AutherFirstName"].ToString();
}
}
return bookList;
}
2条答案
按热度按时间agyaoht71#
I would say configurations in .NET are annoying stuff but, let's skip that ;)
The usage of options is done after some DI logic. So basically, your problem probably is in how you are trying to get the value from
appsettings.{ENV}.json
.You haven't attached this part of the code but when you are calling your method from the
Book.cs
class, you should do something like that:BTW this is an anti-pattern and I strongly recommend you start using the Options Pattern to inject options and settings into your code.
So, your code should be changed to something like that:
Since you are using .net 6, update your
Program.cs
class to add the connection strings as DI Options adding the following line before thevar app = builder. Build();
statement.Example of
appsettings.json
section7ajki6be2#
I eventually came to the answer. Had to change the query in SQL and put part of the code into a try/catch block and it worked.