LINQ to Entities does not recognize the 'System.Web.Mvc.FileResult' method

I am trying to display multiple usernames with their image. So, I have a Json action method similar to this:

public JsonResult GetUsers() { var ret = (from user in db.Users orderby user.UserName select new { UserName = user.UserName, Pic = GetFileData(user.Id), }).AsEnumerable(); return Json(ret, JsonRequestBehavior.AllowGet); } 

And this is my GetFileData method to get the user image:

 public FileResult GetFileData(int Id) { var avatarImage = db.Files.SingleOrDefault(s => s.ApplicationUserId == Id); return File(avatarImage.Content, avatarImage.ContentType); } 

Here ApplicationUserId is the foreign key related to the file and ApplicationUser .

Now, when I run the query, I should get the username with their picture. But I get a System.NotSupportedException . Full error message:

LINQ to Entities does not recognize the 'System.Web.Mvc.FileResult GetFileData (Int32)' method, and this method cannot be translated into a storage expression.

How to solve it. I saw a lot of stackoverflow questions related to it, but none of the questions dealt with FileResult. The code for the watch page is here http://pastebin.com/AyrpGgEm

+1
source share
1 answer

GetFileData cannot be translated into T-SQL, Linq to Entities could not recognize it. You can change the code as shown below (Move GetFileData outside the expression):

 var pic = GetFileData(user.Id); public JsonResult GetUsers() { var ret = (from user in db.Users orderby user.UserName select new { UserName = user.UserName, Pic = pic, }).AsEnumerable(); return Json(ret, JsonRequestBehavior.AllowGet); } 

But since the user does not exist outside the request, you must use .ToList() to defer the use of your function. After .ToList() after loading the data, any further operation (for example, select ) is performed using Linq to Objects, according to the data already in memory. Therefore, your request should look like this:

 public JsonResult GetUsers() { var ret = (from user in db.Users.ToList() orderby user.UserName select new { UserName = user.UserName, Pic = GetFileData(user.Id), }).AsEnumerable(); return Json(ret, JsonRequestBehavior.AllowGet); } 
+2
source

Source: https://habr.com/ru/post/1013330/


All Articles