Reputation: 19
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!
Upvotes: 1
Views: 726
Reputation: 9725
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.
Upvotes: 0
Reputation: 101681
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.
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)
Upvotes: 1