简体   繁体   中英

Entity framework - NotSupportedException in lambda expression

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

In a public static class

I have following methods:

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.

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?

Thanks!

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 (eg using AsEnumerable() ) then do whatever you want.

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 .

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

Try evaluating your function to an Employee first...

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

Although those two lambda expression could be put into one to make it more efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM