简体   繁体   English

实体框架,如何使Sum <>接受方法?

[英]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. 我正在Entity Framework中编写一个数据库,并且我想创建一个可被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() . 所以我知道EF到SQL不会理解“ 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 错误4无法转换类型

'System.Linq.Expressions.Expression>' to 'double' 'System.Linq.Expressions.Expression>'为'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; 并且您的扩展方法必须为此返回double;

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. 另一方面,如果您的目标是要有一些逻辑可以自定义总和下的列,那么您就无法拥有将实体作为参数的方法,则您必须仅知道您的实体的类型并可能不保存一些相关的标识符来构建表达式在实体内部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM