我第一次尝试使用LINQ,不明白如何通过数据库读取。我确信我做了一些完全愚蠢的事情,只是需要一点指导。
year = year.Where(x => x.statementYear == response[i]).ToList();
SqlDataReader reader;
while (reader.Read())
{
}
编辑了问题,提供了更多信息。
这就是我一直在尝试的工作... ... 我想我不需要 con.open()
要么如果我使用的是using语句对吗?
using (SqlConnection con = new SqlConnection(".."))
{
List<string> paths = new List<string>();
// Open Connection
con.Open();
if (response != null)
{
for (var i = 0; i < response.Length; i++)
{
if (response != null)
{
using (var db = new db())
{
List<ClientStatement_Inventory> years = new List<ClientStatement_Inventory>();
years = years.Where(x => x.statementYear == response[i]).ToList();
foreach (var year in years)
{
paths.Add(year.statementPath);
}
}
}
}
}
}
在使用Linq时,没有任何用处,也没有任何意义。SqlDataReader
....
你真的没有表现出太多的东西--但基本上,有了Linq,你应该会有一个 DbContext
(那是你与数据库的 "连接"),而那个 DbContext
应包含任何数量的 DbSet
- 基本上代表了你的数据库中的表。你可以从这些表中选择 DbSet
的,然后你得到回一个 List<Entity>
你只需对其进行迭代。
沿着这样的思路。
-- select your customers matching a certain criteria
var customers = NorthwindDbContext.Customers.Where(x => x.statementYear == response[i]).ToList();
-- iterate over your customers
foreach (Customer c in customers)
{
// do whatever with your "Customer" here
}
UPDATE:
从你更新的问题中,你真正需要的是:
List<string> paths = new List<string>();
using (var db = new FMBDBPRDEntities1())
{
List<ClientStatement_Inventory> years = new List<ClientStatement_Inventory>();
years = years.Where(x => x.statementYear == response[i]).ToList();
foreach (var year in years)
{
paths.Add(year.statementPath);
}
}
打开访问数据库的上下文,把一些数据读到一个列表中, 遍历列表中的元素,就完成了。其他的都是无用的,可以直接删除。
而且你也可以写得更简单。
using (var db = new FMBDBPRDEntities1())
{
List<string> paths = years.Where(x => x.statementYear == response[i])
.Select(y => y.statementPath).ToList();
}
UPDATE #2:如果你的 response
是一个值的集合(我是 假设 这些将是 int
值),你需要对它进行迭代--试试这样的方法。
if (response != null)
{
List<string> allPaths = new List<string>();
using (var db = new FMBDBPRDEntities1())
{
foreach (int aYear in response)
{
List<string> paths = years.Where(x => x.statementYear == aYear)
.Select(y => y.statementPath).ToList();
allPaths.AddRange(paths);
}
}
return allPaths; // or do whatever with your total results
}
UPDATE #3:只是想知道--似乎你从来没有真正访问过。DbContext
根本......。我只是 猜测 但类似这样的事情:
if (response != null)
{
List<string> allPaths = new List<string>();
using (var db = new FMBDBPRDEntities1())
{
foreach (int aYear in response)
{
// access a DbSet from your DbContext here!
// To actually fetch data from the database.....
List<string> paths = db.ClientStatement_Inventory
.Where(x => x.statementYear == aYear)
.Select(y => y.statementPath).ToList();
allPaths.AddRange(paths);
}
}
return allPaths; // or do whatever with your total results
}