简体   繁体   中英

Why does this Linq-to-SQL query not cast the objects when performing the Where clause?

I have a Linq query similar to as follows,

var dataByWheels = this.Db.Cars.Cast<IVehicle>().Where(v => (v.NumWheels == 4));

IVehicle in this case is an interface which defines that the class must have a NumWheels property. The Cars class is similar to as follows,

[Table]
public class Car : IVehicle
{
     [Column]
     public double Weight { get; set; }

     ...

     public int NumWheel 
     {
         get { return 4; }
     }
}

So in this case the NumWheels property is not stored in the database, however if the cast is done then it should be OK. However an exception is raised,

The member 'MyProject.IVehicle.NumWheels' has no supported translation to SQL

Which implies that it is not performing th cast. When I insert a ToList() into the chain after Cast it does work but I imagine this is prematurely resolving the query and creating a giant List of the entire table and would like to avoid since I am working on the phone .

What am I doing wrong?

(Note I changed the names and queries to make this simpler)

This is happening because when you issue a Where statement against a LINQ to SQL class, the LINQ to SQL engine expects that you are performing a WHERE statement against the database directly and tries to map the statement to raw T-SQL which it cannot do since NumWheels is not a database column.

To overcome this, you COULD do a ToList on it first, but beware of the performance implications if you do. This code will cycle through the entire Cars table and do the filtering in-memory. I can't think of another way to accomplish your goal, however.

var dataByWheels = this.Db.Cars.ToList().Where(v => (v.NumWheels == 4));

The problem isn't your LINQ, but rather your use context. This particular LINQ query is being used on a Queryable and the Cast will force it to go to the DB and pull back all the results at that point. You can then do the cast on the enumerable and proceed, but it may very well not be what you are looking for in this case.

The error simply indicates that you have written an expression that can not be mapped to SQL and executed on the SQL server. It's an EF thing, not a LINQ thing.

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