简体   繁体   中英

SqlDataReader: SqlException - Invalid object name (table)

This service gets data from the API, checks for duplicates and saves it to the DB. Error occurs when SqlDataReader trying to retrieve data from table. When this code was in the ASP.NET project, everything was working fine.

List<Thumbnail> Thumbnails = new List<Thumbnail>();

var client = new HttpClient
{
    BaseAddress = new Uri("https://api.spaceflightnewsapi.net/v3/articles?_limit=100")
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(client.BaseAddress);
if (response.IsSuccessStatusCode)
{
    Thumbnails = JsonConvert.DeserializeObject<List<Thumbnail>>(response.Content.ReadAsStringAsync().Result);
}

if (Thumbnails != null)
{
    for (int i = 0; i < Thumbnails.Count; i++)
    {
        Thumbnails[i].PublishedAt = Thumbnails[i].PublishedAt.ToUniversalTime();
    }

    SqlConnection conn = new SqlConnection(connectionString);
    conn.Open();
    SqlCommand cmdr = new SqlCommand("SELECT * FROM mobilesdb.dbo.thumbnails ORDER BY PublishedAt", conn)
    {
        CommandType = CommandType.Text
    };
    SqlDataReader reader = await cmdr.ExecuteReaderAsync();//error: System.Data.SqlClient.SqlException: 'Invalid object name 'mobilesdb.dbo.thumbnails'.'

    try
    {
        while (reader.Read())
        {
            Thumbnail thumbnail = new Thumbnail()
            {
                Title = reader.GetString(1),
                Url = reader.GetString(2),
                ImageUrl = reader.GetString(3),
                NewsSite = reader.GetString(4),
                Summary = reader.GetString(5),
                PublishedAt = reader.GetDateTime(reader.GetOrdinal(nameof(thumbnail.PublishedAt))),
                UpdatedAt = reader.GetDateTime(reader.GetOrdinal(nameof(thumbnail.UpdatedAt))),
            };

            for (int i = 0; i < Thumbnails.Count; i++)
            {
                if (Thumbnails[i].Title.Equals(thumbnail.Title) &&
                    Thumbnails[i].NewsSite.Equals(thumbnail.NewsSite) &&
                    Thumbnails[i].Summary.Equals(thumbnail.Summary))
                {
                    Thumbnails.RemoveAt(i);
                }
            }
        }
    }
    catch (Exception) { }

    reader.Close();

This is part of code that responsible for receiving data from API and checking for duplicates. Error occurs after initializing SqlDataReader object. The same code for retrieving data from database is in ASP.NET project and works perfectly, so problem isn't in sql request.
PS
Additional info from console (debug): Exception thrown: 'System.Data.SqlClient.SqlException' in mscorlib.dll An exception of type 'System.Data.SqlClient.SqlException' occurred in mscorlib.dll but was not handled in user code Invalid object name 'thumbnails'.

Well, I solved my question. Since the problem concerned the connection to the database, I decided to deal with the connection string first. In my case it's - private static readonly string connectionString = "Server=(localdb)\\MSSQLLocalDB; Database=mobilesdb; Initial Catalog=mobilesdb; Trusted_Connection=True;";
After that, I changed the Log on parameter from the Local System account to my own in the service properties and everything started working correctly. Thanks to everyone who tried to help.

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