【问题标题】:Get Results from Linq query(System.Data.Entity.Infrastructure.DbQuery) and convert to List从 Linq 查询(System.Data.Entity.Infrastructure.DbQuery)获取结果并转换为列表
【发布时间】:2019-05-13 18:16:58
【问题描述】:

我有一个 linq 查询,它从表中返回多行,我想获取行数,并将结果从 System.Data.Entity.Infrastructure.DbQuery 更改为 List。 strUserID 不是客户服务表的主键。

var AllCustomerServices = from service in _context.CustomerServices
    where service.strUserID == Session["userID"].ToString()
    select service;

以下代码抛出异常:

if (AllCustomerServices.Count() > 0)
{
    List<CustomerServices> cstSrvs = AllCustomerServices.ToList();
}

例外:

“AllCustomerServices.ToList()”引发了“System.NotSupportedException”类型的异常 [NotSupportedException:LINQ to Entities 无法识别方法 'System.Object get_Item(System.String)' 方法,并且该方法无法转换为存储表达式。]

【问题讨论】:

  • 您好。您能否提供完整的异常堆栈?
  • @JuanR [NotSupportedException: LINQ to Entities 无法识别方法 'System.Object get_Item(System.String)' 方法,并且此方法无法转换为存储表达式。]

标签: c# asp.net linq model-view-controller


【解决方案1】:

先尝试将会话值放入变量中:

var value = Session["userID"].ToString(); //Watch out for nulls, by the way

var AllCustomerServices = from service in _context.CustomerServices
where service.strUserID == value
select service;

错误消息表明 LINQ to Entities 正在尝试将对 Session["UserID"] 的调用转换为可以在商店中执行的内容,而实际上,您需要传递给商店的只是实际值。

【讨论】:

    【解决方案2】:

    应该可以,但我不明白,为什么你尝试将 List 放在另一个 List 中

    var AllCustomerServices = _context.CustomerServices.Where(w=>w.strUserID == Session["userID"].ToString()).ToList();
    
        if (AllCustomerServices.Any())
        {
            List<CustomerServices> cstSrvs = new List<CustomerServices>();
            cstSrvs.AddRange(AllCustomerServices);
        }
    

    P.S 是 var AllCustomerServices 已经是 List&lt;CustomerServices&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 2010-10-31
      • 1970-01-01
      相关资源
      最近更新 更多