0

I have such piece of code and after execution I get N rows in my database table and N-1 rows data are returned from method. Can't understand what I'm doing wrong and find any examples of similar problem. Does I lose data because of sql query, or I did a mistake in a code? Please, help.

    private String sqlCommandSample = "insert into [dbo].[SomeTable] " +
                         "(Title, Descript) " +
                         "output inserted.Title " +
                         "select Item.value('title[1]', 'nvarchar(max)'), Item.value('description[1]', 'nvarchar(max)') " +
                         "from @Xml.nodes('nodes/node') as Result(Item) " +
                         "where not exists (select * from [dbo].[SomeTable] " +
                         "where ([Title] = Item.value('Title[1]', 'nvarchar(200)')))";

    public async Task<List<String>> FillTableAsync(String sqlCommandString, GetArticleLink getArticleLink)
    {
        using (var sqlConnection = new SqlConnection(ConnectionString))
        {
            await sqlConnection.OpenAsync();

            using (var sqlCommand = new SqlCommand(sqlCommandString, sqlConnection))
            {
                using (var sqlReader = await sqlCommand.ExecuteReaderAsync())
                {
                    var listOfLinks = new List<String>();

                    if (await sqlReader.ReadAsync())
                    {
                        while (await sqlReader.ReadAsync())
                        {
                            listOfLinks.Add(await GetLink(sqlReader));
                        }
                    }
                    return listOfLinks;
                }
            }
        }
    }

    private async Task<String> GetLink(DbDataReader reader)
    {
        return await reader.GetFieldValueAsync<String>(0);
    }

1 Answer 1

4
 if (await sqlReader.ReadAsync())
 {
     while (await sqlReader.ReadAsync())
     ...

Here you just lost a row. while is enough, no need for if.

Sign up to request clarification or add additional context in comments.

2 Comments

You're right! Thank you very much! Need to be more accurate next time.
You can use the HasRows property to check if there are rows

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.