Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

System.IndexOutOfRangeException: Id – SQL C#

I am reading from my database performing an inner join clause in c#. Whenever it hits the line
x.Id = (int)reader["Id"]; it says "System.IndexOutOfRangeException: Id". I know that error displays when it does not exist in the db. But on ssms when I run the cmd

select ItemName
from MainStore
inner join SecondStore
on MainStore.Id = SecondStore.Id

which returns

ItemName

Candy

Marshmallow

In c# I do,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        List<MainStore> storeList = new();

        SqlConnection connection = new();

        using (connection = new SqlConnection(_connectionString))
        using (SqlCommand command = new SqlCommand("select ItemName from MainStore inner join SecondStore on MainStore.Id = SecondStore.Id", connection))
        {
            connection.Open();

            using SqlDataReader reader = command.ExecuteReader();


            while (reader.Read())
            {
                var x = new MainStore();

                x.ItemName = reader["ItemName"].ToString();
                x.Id = (int)reader["Id"];
                x.SecondStore.Id = (int)reader["Id"];

                storeList.Add(x);
            }

        }

both lines x.Id and x.SecondStore.Id give me the same error. Why is that?

public class MainStore
{
    public int Id { get; set; }
    public string ItemName { get; set; }
    public SecondStore SecondStore { get; set; }
}

public class SecondStore
{
    public int SecondStoreId { get; set; }
    public int Id { get; set; }
}

>Solution :

Change your query

"select ItemName, MainStore.Id as MainStoreId, SecondStore.Id as SecondStoreId from MainStore inner join SecondStore on MainStore.Id = SecondStore.Id", connection))

But I think you have a bug in your query relations. Pls post the MainStore and the SecondStore classes.

and code

 x.ItemName = reader["ItemName"].ToString();
 x.Id = (int)reader["MainStoreId"];

SecondStore.Id is the same as MainStoreId. You will have to create then SecondStore object too, but I can’t see why do you need it

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading