实体框架 - NotSupportedException异常的Lambda前pression [英] Entity framework - NotSupportedException in lambda expression

查看:164
本文介绍了实体框架 - NotSupportedException异常的Lambda前pression的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MVC应用程序的 ApplicationUser 员工类有1-1的关系:

In my MVC application ApplicationUser and Employee classes have 1-1 relationship:

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));
            }
        }

你可以看到第二个方法消耗的第一个方法。
但我发现了以下错误:

as you can see second method is consuming the first method. But I'm getting the following error:

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.

但是,如果我贴我的第一个方法内内code到我的第二个方法如下图所示,它工作正常。

But if I paste the inner code inside my first method to my second method like below, it works fine.

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

什么,我在这里丢失?
为什么我得到这个错误?

What I'm missing here? Why I'm getting this error?

谢谢!

推荐答案

GetCurrentApplicationUser 方法不能转换成SQL。如果你想使用查询自定义方法,你将不得不加载记录到内存中(如使用 AsEnumerable()),然后做你想做的。

GetCurrentApplicationUser method can not be translated into SQL. If you wanna use a custom method in your query you will have to load the records into memory (e.g using AsEnumerable()) then do whatever you want.

您可能会想,该方法只是执行另一个查询并返回结果,所以它应该被翻译成 SQL 但可以在pretty任何东西你的方法,但不保证如此,它是<青霉>不受支持的

You might be thinking that the method just performs another query and returns the result, so it should be translated into SQL but there can be pretty much anything in your method, there is no guarantee so, it is unsupported.

有关详细信息,请参见支持和不支持LINQ方法(LINQ到实体)

For more information see Supported and Unsupported LINQ Methods (LINQ to Entities)

这篇关于实体框架 - NotSupportedException异常的Lambda前pression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆