I have a problem sending data from the database to a list in the Controller. I am new to C# and MVC so any help will be useful! Code follows
将数据从数据库发送到控制器中的列表时出现了问题。我是c#和MVC的新手,所以任何帮助都是有用的!代码如下所示
public static List<FilterTree> GetAllUsers()
{
FilterTreeDBContext db = new FilterTreeDBContext();
var userList = new List<FilterTree>();
var device = new FilterTree();
//This is the line where I get the error
device.ID = from a in db.FilterTree select a.ID;
userList.Add(device);
return userList;
}
Thanks & Happy Holidays!! :)
谢谢&节日快乐! !:)
2 个解决方案
#1
12
device.ID = (from a in db.FilterTree select a.ID).First();
Linq query is lazy, and executes only after you request the value
Linq查询是惰性的,只有在请求值之后才执行
BTW don't forgot to close the context, otherwise you will leak connections
顺便说一下,不要忘记关闭上下文,否则会泄漏连接。
using (var db = new FilterTreeDBContext())
{
...
return userList;
}
#2
2
As far as the frameworks knows that query may have more than one object so use it like this:
就框架所知,查询可能有多个对象,因此可以这样使用:
device.ID = (from a in db.FilterTree select a.ID).FirstOrDefault();
#1
12
device.ID = (from a in db.FilterTree select a.ID).First();
Linq query is lazy, and executes only after you request the value
Linq查询是惰性的,只有在请求值之后才执行
BTW don't forgot to close the context, otherwise you will leak connections
顺便说一下,不要忘记关闭上下文,否则会泄漏连接。
using (var db = new FilterTreeDBContext())
{
...
return userList;
}
#2
2
As far as the frameworks knows that query may have more than one object so use it like this:
就框架所知,查询可能有多个对象,因此可以这样使用:
device.ID = (from a in db.FilterTree select a.ID).FirstOrDefault();