我想知道如何将 SqlDataReader 转换为 LINQ 方式?
这是我的 SqlDataReader 代码。
string strConn = "server=xxx.com;database=mydb;User ID=test;Password=test;Trusted_Connection=true;";
SqlConnection myConn = new SqlConnection(strConn);
myConn.Open();
string strSQL = "select period from timetable_view where identity_num = '" + Identity_NUM + "' week = '3'";
SqlCommand myCommand = new SqlCommand(strSQL, myConn);
SqlDataReader myDataReader = myCommand.ExecuteReader();
int Count = Add_CourseConfirmedQuery.Count();
Random rnum = new Random();
string[] arr = new string[Count];
for (int i = 0; i < Count; i++)
{
myDataReader.Read();
arr[i] = myDataReader["period"].ToString();
}
ViewBag.test = arr[0];
ViewBag.test2 = arr[1];
myCommand.Cancel();
myDataReader.Close();
myConn.Close();
myConn.Dispose();
string[] input2 = new string[Count];
for (int i = 0; i < Count; i++)
{
input2[i] = arr[i];
}
这段代码工作正常。
我尝试在 LINQ 中编写代码,但它不起作用。
这是我尝试过的 LINQ 代码,但我不知道如何提取 的所有记录a.identity_num
,并将它们放入一个数组中,如上面的代码(SqlDataReader)。
var test = from a in timetable_view
where a.identity_num = Identity_NUM && a.week = "3"
select a new{a.identity_num};
ViewBag.test = test.FirstOrDefault();
[更新问题]
这就是我现在正在尝试的。
我无法从我的表中提取正确的记录。
但是页面显示:System.String[]
var Query = from m in db.members
join d in db.departments on m.department equals d.department_id
join s in db.select_list on m.member_id equals s.member_id
join c in db.courses on s.kkk_id equals c.kkk_id
join t in db.teachers on c.teacher equals t.teacher_id
where m.identity_num == Identity_NUM && c.week == "3"
select c.period;
var PA = Query.ToArray();
int Count = Query.Count();
string[] arr = new string[Count];
for (int i = 0; i < Count; i++)
{
arr[i] = PA.ToString();
}
ViewBag.test = arr[0];
ViewBag.test2 = arr[1];
.............
............
...........
string[] input2 = new string[Count];
for (int i = 0; i < Count; i++)
{
input2[i] = arr[i];
}
.............
............
...........