SQL Query只返回一个项目(而不是完整列表) - asp.net mvc [英] SQL Query only returns one item (rather than complete list) - asp.net mvc

查看:50
本文介绍了SQL Query只返回一个项目(而不是完整列表) - asp.net mvc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.NET中有一个SQL查询,但它似乎只返回1个结果,而不是用4填充列表(因为查询本身是正确的)



代码:



I have an SQL query within ASP.NET, but it only seems to return 1 result rather than filling the list with 4 as it should (as the query itself is correct)

Code:

List<string> dropItems, dropItems2;

using (var dbContext = new DatabaseContext())
{
    dropItems = dbContext.Database.SqlQuery<String>(
        String.Format("SELECT locations.Code FROM locations")).ToList();
}
using (var dbContext = new DatabaseContext())
{
    dropItems2 = dbContext.Database.SqlQuery<String>(
        String.Format("SELECT locations.Name FROM locations")).ToList();
}





代码执行后,每个列表只包含一个项目而不是4个它们都应该



FYI - 我总是收到的项目而不是全部4只是最后一项



After the code executes, each list only contains one item rather than 4 which they both should

F.Y.I - The item I'm always receiving rather than the full 4 is just the last one

推荐答案

你应该像这样更改你的代码:

You should change your code like this:
List<string> dropItems, dropItems2;

using (var dbContext = new DatabaseContext())
{
    dropItems = dbContext.Locations.Select( l => l.Code).ToList();
    dropItems2 = dbContext.Locations.Select( l => l.Name).ToList();
}


你的代码与我一起工作..

我找不到原因,你不是得到结果..



尝试不同的代码..我想这会解决你的问题。

Your Code Working Fine With me..
I can't find out why, you are not getting the result..

Try different code..I think this will solve your problem.
List<string> dropItems, dropItems2;
 
using (var dbContext = new DatabaseContext())
{
var data = from o in dbContext.locations select new { o.Code };
foreach (var str in data)
{
 if(str!=null)
 {
  dropItems .Add(str.ToString());
 }
}
//dropItems = dbContext.Database.SqlQuery<string>(
 //String.Format("SELECT locations.Code FROM locations")).ToList();
}
using (var dbContext = new DatabaseContext())
{
var data1 = from o in dbContext.locations select new { o.Name };
foreach (var str1 in data1)
{
 if(str1!=null)
 {
  dropItems2 .Add(str1.ToString());
 }
}

    //dropItems2 = dbContext.Database.SqlQuery<string>(
        //String.Format("SELECT locations.Name FROM locations")).ToList();
}

</string></string></string>


这篇关于SQL Query只返回一个项目(而不是完整列表) - asp.net mvc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆