简体   繁体   中英

Entity Framework, how to get Sum<> accept a method?

I'm a little bit stuck, and I not sure this is possible. I'm writting a database in Entity Framework, and I want to make a method which can be used in by dataconext.

So I want to write something like....

double total = db.FlightEntries().Sum(f => f.GetTotalflightTimes());

So I know EF to Sql wont understand " GetTotalflightTimes() .

So I wote this...

public static class MyFlightEntryExtentions
{
    public static Expression< Func<FlightEntry, double>> GetTotalFlightTimes(this FlightEntry flightEntry)
    {
        double value
         ...........
         ..........
        return x => value;
    }
} 

Error 4 Cannot convert type

'System.Linq.Expressions.Expression>' to 'double'

I know I could be going the wrong way about this, so can someome tell me!

It is a little bit unclear what you want to achieve but if you want to execute some custom sum logic that is not simply pointing to property/column in database you need to finalize query first and than on already read objects you can perform you sum:

db.FlightEntries().ToArray().Sum(f => f.GetTotalflightTimes());

And your extension method must return double for that;

If on other hand your goal is to have some logic that customizes the column under the sum you cannot have method that has an entity as parameter you have to build the expression only knowing the type of your entity and maybe some related discriminator that is not saved inside the entity.

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