我正在從我的資料庫中讀取在 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; }
}
uj5u.com熱心網友回復:
更改您的查詢
"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 物件,但我不明白你為什么需要它
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/349946.html
上一篇:使用索引時如何保證一致性?
