【问题标题】:Cannot convert type 'System.Linq.IQueryable<int>' to 'int'无法将类型“System.Linq.IQueryable<int>”转换为“int”
【发布时间】:2013-12-18 14:18:15
【问题描述】:

我在将数据从数据库发送到控制器中的列表时遇到问题。我是 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;
    }

谢谢,节日快乐!! :)

【问题讨论】:

  • 问题官有什么问题?
  • FilterTree 是您的数据库集。因此,从您的查询中,您将获得一个整数列表。 FilterTree 中实例变量 ID 的类型是什么?我想从你得到的错误中可以明显看出它是 int 的。您正在尝试将列表 (Iqueryable) 存储到 int 字段。我希望此分析能帮助您解决问题。
  • 感谢@AbhinavRanjan 的解释!

标签: c# database asp.net-mvc-4 controller


【解决方案1】:
device.ID = (from a in db.FilterTree select a.ID).First();

Linq 查询是惰性的,只有在你请求值后才会执行

顺便说一句,不要忘记关闭上下文,否则会泄漏连接

using (var db = new FilterTreeDBContext())
{
    ...
    return userList;
}

【讨论】:

  • @Mihai-CristianRotariu,既然如此,请确保在时间过去后接受它作为答案。
【解决方案2】:

就框架所知,查询可能有多个对象,所以像这样使用它:

device.ID = (from a in db.FilterTree select a.ID).FirstOrDefault();

【讨论】:

    猜你喜欢
    • 2011-02-04
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多