[英]System.IndexOutOfRangeException: Id - SQL C#
我正在从我的数据库中读取在 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; }
}
更改您的查询
"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 对象,但我不明白你为什么需要它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.