【问题标题】:Entity framework - NotSupportedException in lambda expression实体框架 - lambda 表达式中的 NotSupportedException
【发布时间】:2014-10-09 20:54:35
【问题描述】:

在我的 MVC 应用程序中,ApplicationUserEmployee 类具有 1-1 关系:

public class ApplicationUser : IdentityUser
    {
        public Employee Employee { get; set; }
    }

public class Employee
    {
        [Key]
        public virtual ApplicationUser ApplicationUser { get; set; }
        public virtual string Name { get; set; }
    }

公共静态类中

我有以下方法:

public static ApplicationUser GetCurrentApplicationUser(string userName)
        {
            using (DbContext db = new DbContext())
            {
                return db.Users.FirstOrDefault(u => u.UserName.Equals(userName));
            }
        }

public static Employee GetEmployeeByApplicationUser(string userName)
        {
            using (DbContext db = new DbContext())
            {
                return db.Employees.SingleOrDefault(e => e.ApplicationUser == GetCurrentApplicationUser(userName));
            }
        }

如您所见,第二种方法正在使用第一种方法。 但我收到以下错误:

System.NotSupportedException was unhandled by user code
Message=LINQ to Entities does not recognize the method 'GetCurrentApplicationUser(System.String)' method, and this method cannot be translated into a store expression.

但是,如果我将第一个方法中的内部代码粘贴到第二个方法中,如下所示,它可以正常工作。

return db.Employees.SingleOrDefault(e => e.ApplicationUser == db.Users.FirstOrDefault(u => u.UserName.Equals(userName)));

我在这里缺少什么? 为什么会出现此错误?

谢谢!

【问题讨论】:

    标签: c# linq linq-to-entities asp.net-mvc-5 entity-framework-6


    【解决方案1】:

    GetCurrentApplicationUser 方法无法翻译成 SQL。如果您想在查询中使用自定义方法,则必须将记录加载到内存中(例如使用 AsEnumerable()),然后做任何您想做的事情。

    您可能认为该方法只是执行另一个查询并返回结果,所以它应该被翻译成SQL 但您的方法中几乎可以有任何东西,不能保证,它是 不支持

    欲了解更多信息,请参阅Supported and Unsupported LINQ Methods (LINQ to Entities)

    【讨论】:

    • 您能告诉我如何在上面的示例中使用 AsEnumerable() 吗?谢谢@Selman22
    • @nanyanjan 在这种情况下,您不需要 AsEnumerable。只需在查询之外调用 GetCurrentApplicationUser 方法,获取 Employee 并在您的查询中使用它,如下面的答案所示。
    • @nanyanjan 猜他的意思是我的答案。
    【解决方案2】:

    尝试先将您的功能评估为员工...

    using (DbContext db = new DbContext())
    {
        db.Connection.Open();
    
        Employee currentApplicationUser = db.Users.FirstOrDefault(u => u.UserName.Equals(userName));
    
        currentApplicationUserEmployee = db.Employees.SingleOrDefault(e => e.ApplicationUser == currentApplicationUser);
    
        db.Connection.Close();
    
        return currentApplicationUserEmployee;
    }
    

    虽然这两个 lambda 表达式可以合二为一,以提高效率。

    【讨论】:

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