簡體   English   中英

實體框架-Lambda表達式中的NotSupportedException

[英]Entity framework - NotSupportedException in lambda expression

在我的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)));

我在這里想念的是什么? 為什么我會收到此錯誤?

謝謝!

GetCurrentApplicationUser方法無法轉換為SQL。 如果要在查詢中使用自定義方法,則必須將記錄加載到內存中(例如,使用AsEnumerable() ),然后執行所需的任何操作。

您可能會認為該方法只是執行另一個查詢並返回結果,因此應將其轉換為SQL但您的方法中幾乎可以包含任何內容,因此不能保證,因此不受支持

有關更多信息,請參見受支持和不受支持的LINQ方法(LINQ到實體)

嘗試先評估員工的職能...

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表達式合而為一,以提高效率。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM