Error, method not supported by LINQ to Entities

2020-02-06 06:17发布

Why I am getting this error:

The method 'Single' is not supported by LINQ to Entities. Consider using the method 'First' instead.

           public ActionResult Details(int id)
Line 27:   {              
             var result = (from d in _db.MovieSet
Line 29:     where d.Id == id
Line 30:     select d).Single();
            //
            //
           } 

Code compiles safe, but only breaks if call is made to the respective section. I am new to LINQ, therefore do not know which methods are for LINQtoSQL or LINQtoEntities. This means more errors! We cannot remember all methods this way.

My question is, if there are limitations to the methods applicable to certain types / scenarios, why do they appear in Intellisense?

EDIT: Any work-around / technique helpful to have an idea if one is supported ?

3条回答
祖国的老花朵
2楼-- · 2020-02-06 06:48

In the case of LINQtoSQL / Entities, the queries are all broken down into expression trees which are then passed to the provider APIs. The providers cannot provide compile time information about the trees they do or do not support because there is no syntactic difference. The only choice is for them to provide runtime data.

For example once in expression tree form, both the Single and First appear as a MethodCallExpression instance.

查看更多
Ridiculous、
3楼-- · 2020-02-06 06:48

Unfortunately, it's yet another indication of both the relative immaturity of EF and the Object Relational Impedance Mismatch.

Documentation is your friend if you choose to go this route.

查看更多
Evening l夕情丶
4楼-- · 2020-02-06 07:05

Microsoft has a complete list of supported and unsupported methods in Linq to Entities. That's where to go to find out this information.

You'll notice that the Single and SingleOrDefault methods are in fact listed as "not supported" in the section on Paging Methods.

As Jared pointed out, the compiler does not know at compile time which provider you are using, so it has no way to enforce compile-time safety of extension methods that the provider may or may not implement. You'll have to rely on the documentation instead.

查看更多
登录 后发表回答