【问题标题】:c# LINQ to Entities does not recognize the method 'System.String ToString()' methodc# LINQ to Entities 无法识别方法 'System.String ToString()' 方法
【发布时间】:2014-12-26 06:40:52
【问题描述】:

我想在数据库中选择多个列并存储在数组中,但一直收到此错误

LINQ to Entities 无法识别方法“System.String ToString()”方法,并且该方法无法转换为存储表达式。

它应该返回类似“FunctionCode-ActivityCode”的东西

public override string[] GetRolesForUser(string username)
{
    DEV_Context OE = new DEV_Context();
    string role = OE.UserRefs.Where(x => x.UserName == username).FirstOrDefault().RoleName;

    string[] result = OE.RolePermissionRefs
        .Where(x => x.RoleName == role && x.StatusCode == "A")
        .Select(x => new { FunctionCode = x.FunctionCode, ActivityCode = x.ActivityCode }.ToString())
        .ToArray();

    return result;
}

【问题讨论】:

    标签: c# linq entity-framework


    【解决方案1】:

    ToString() 仅在 EF 6.0 及更高版本中可用。在您的情况下,您可以在 Select 之前调用 ToArray() 并执行 Selman 建议的操作。

    【讨论】:

      【解决方案2】:

      即使它可以工作,它也不会给你预期的结果。你在匿名对象上调用ToString。如果您只想连接值,可以尝试:

      string[] result = OE.RolePermissionRefs
              .Where(x => x.RoleName == role && x.StatusCode == "A")
              .Select(x => new { x.FunctionCode, x.ActivityCode })
              .AsEnumerable()
              .Select(x => string.Join("-", x.FunctionCode, x.ActivityCode))
              .ToArray();
      

      ToString不起作用的原因已经在错误信息中解释了。它不能被翻译成SQL。所以你需要将结果加载到内存中(例如在上面的代码中使用AsEnumerable)和然后投影它们。

      【讨论】:

      • 也可以使用x => string.Format("{{ FunctionCode = {0}, ActivityCode = {1} }}", x.FunctionCode, x.ActivityCode) 代替Join。这应该看起来像匿名类型上的 ToString 实现,但实际上没有创建一个实例。
      猜你喜欢
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-25
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多