简体   繁体   中英

System.NotSupportedException when trying to get an element from list

The error also shows this:

LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[System.String] GetRoleById(Int32)' method, and this method cannot be translated into a store expression.

I only want to list the elements where the Role of a User equals Bereichsleitung .

GetRoleByID returns a List of string

 var model =
                db.Urlaubantrag.OrderByDescending(x => x.Jahr)
                    .Where(a => userdao.GetRoleById(a.Urlauber_ID).Contains("Bereichsleitung"))
                    .ToPagedList(page, pageSize);
            return View(model);

Anybody got an idea where the exact problem might be?

Firstly, It's not LINQ to Entities , it's LINQ to SQL . And problem - LINQ to SQL can not translate method GetRoleById into sql code.

You can load all data from table and filter in code like this:

 var model =
             db.Urlaubantrag.OrderByDescending(x => x.Jahr)
                 .ToArray()
                 .Where(a => userdao.GetRoleById(a.Urlauber_ID).Contains("Bereichsleitung"))
                 .ToPagedList(page, pageSize);

This way is very unoptimal, because it load many rows that can be filtered.

So, you need to analize your GetRoleById and replace it with methods, that can be translated to sql.

You cannot call methods inside the expression. You need to first materialize the queries you are referring first and then use the materialized lists in the queries.

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