【问题标题】:LINQ to Entities does not recognize the method ... method, and this method cannot be translated into a store expression.LINQ to Entities 无法识别方法...方法,并且此方法无法转换为存储表达式。
【发布时间】:2016-08-07 10:58:54
【问题描述】:

MVC 5,C# - 我正在根据数据库中的不同数据集创建视图模型。我有以下代码来创建视图模型。

    public ActionResult Register_step6()
    {
        CoreGeneral cg = new CoreGeneral();

        var model = (from p in db.WorkPointRoles
                     select new RegisterEmployee_Step6Model()

                     {
                         Role = p.Role,
                         Selected = false,
                         RoleDescription = cg.GetRoleDescription(p.Id)
                     });

        return View(model);

    }

我收到以下错误消息:

LINQ to Entities 无法识别方法 'System.String GetRoleDescription(Int32)' 方法,该方法不能 翻译成商店表达式。

我知道该消息与实体无法识别我的 GetRoleDescription 代码有关,因为它位于 select 语句中 - (我的理解可能措辞不正确).. 无论如何,我该如何解决这个问题,我可以将 GetRoleDescription 放在哪里,以便它在返回的每条记录上运行?

我希望这对某人有意义!为措辞不当的问题道歉。提前致谢!

【问题讨论】:

  • GetRoleDescription 是做什么的?

标签: c# asp.net


【解决方案1】:

您应该在内存中而不是 SQL Server 端执行投影到RegisterEmployee_Step6Model

public ActionResult Register_step6()
{
    CoreGeneral cg = new CoreGeneral();

    var model = (from p in db.WorkPointRoles
                 select p).AsEnumerable()
               .Select(r => new RegisterEmployee_Step6Model()
                 {
                     Role = r.Role,
                     Selected = false,
                     RoleDescription = cg.GetRoleDescription(r.Id)
                 });

    return View(model);

}

【讨论】:

  • 谢谢,效果很好!这是一个我还不太热衷的领域!
  • 您可以省略第一个选择查询并只使用db.WorkFopintRoles.AsEnumerable().Select(...)select 查询仅用于您的 LINQ 查询。
猜你喜欢
  • 2015-04-02
  • 1970-01-01
  • 2011-08-19
  • 1970-01-01
  • 2011-08-23
  • 2019-10-31
  • 2012-12-02
相关资源
最近更新 更多