【发布时间】: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.Id或x.SecondStore.Id对吗? @JonSkeet -
我不知道您所说的“我们需要将它包含在 reader.read() 中”是什么意思 - 如果您需要该值,您应该在 SQL 中选择它。如果您不需要该值,请不要尝试读取它。
-
现在更有意义了。谢谢你的澄清!