【问题标题】:System.IndexOutOfRangeException: Id - SQL C#System.IndexOutOfRangeException: Id - SQL C#
【发布时间】:2021-12-19 14:20:28
【问题描述】:

我正在从我的数据库中读取数据,并在 C# 中执行内部连接子句。每当它击中线 x.Id = (int)reader["Id"]; 它说“System.IndexOutOfRangeException: Id”。我知道当数据库中不存在错误时会显示该错误。但是当我运行 cmd 时在 ssms 上

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

返回

ItemName

Candy

Marshmallow

在 c# 中我会这样做,

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

        }

x.Id 和 x.SecondStore.Id 这两行都给了我同样的错误。这是为什么呢?

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

【问题讨论】:

  • 如您所见,结果只有“ItemName”列,因为这就是您选择的所有内容。为什么你认为reader["Id"] 是有效的?
  • 是的,我只想要 ItemName。通过阅读这篇文章w3schools.com/sql/sql_join_inner.asp,我认为在将 sql cmd 转换为 c# 时,我们需要将其包含在 reader.read() 中。所以在我的情况下,我不需要做x.Idx.SecondStore.Id 对吗? @JonSkeet
  • 我不知道您所说的“我们需要将它包含在 reader.read() 中”是什么意思 - 如果您需要该值,您应该在 SQL 中选择它。如果您不需要该值,请不要尝试读取它。
  • 现在更有意义了。谢谢你的澄清!

标签: c# sql


【解决方案1】:

更改您的查询

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

但我认为您的查询关系存在错误。请发布 MainStore 和 SecondStore 类。

和代码

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

SecondStore.Id 与 MainStoreId 相同。您还必须创建 SecondStore 对象,但我不明白您为什么需要它

【讨论】:

  • 没想到使用别名很好知道!谢谢您的帮助!抱歉,我意识到我的模型课有问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多